【问题标题】:one-to-many relation and multiple conditions using Criteria使用 Criteria 的一对多关系和多个条件
【发布时间】:2014-05-15 13:16:11
【问题描述】:

我有 2 张桌子:

  1. 主控table 具有某些对象的单一属性(id, name, title, ...)
  2. 具有重复属性的表(master_id, attribute_name, attribute_value)

#2 的示例数据:

 - 10, "authors", "John Bill"
 - 10, "authors", "Merry J"
 - 10, "owners", "Chris O."
 - 11, "authors", "Andrew K."

这是一个一对多的关系:

<set name="repeating" table="xxx" cascade="none" mutable="false" lazy="true"    fetch="join">
<key column="...."/>
<one-to-many class="...." />
</set>

我想找到主对象(id=10),其中"authors" = "John Bill""authors" = "Merry J""owners" = "Chris O."

对于第一个条件,我可以这样做:

session.createCriteria(Master.class)
.createCriteria("repeating")
.add(Restrictions.eq("attributeName", "authors"))
.add(Restrictions.eq("attributeValue", "John Bill"))
.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY).list();

如何使用 Criteria 添加其他条件?

谢谢

【问题讨论】:

    标签: hibernate one-to-many criteria hibernate-criteria restrictions


    【解决方案1】:

    我猜你想要的是分离标准

    DetachedCriteria dc = DetachedCriteria.forEntityName("repeating")
        .add(Restrictions.eq("attributeName", "authors"))
        .add(Restrictions.eq("attributeValue", "John Bill"))
        // other rows
        .setProjection(Projections.distinct(Property.forName("masterId")));
    
    session.createCriteria(Master.class)
        .add(Property.forName("id").in(dc))
        .list();
    

    【讨论】:

    • 谢谢,但不行。 “owners”是“attributeName”的值。这意味着它应该以这种方式完成:.add(Restrictions.eq("attributeName", "owners")) .add(Restrictions.eq("attributeValue", "Chris O.")) 但在这种情况下它不会返回任何结果。
    • 对不起我的错误。那么我建议你使用Restrictions.disjunction() 来构建你的标准,或者在这种情况下,你可能会发现 HQL 更容易编写。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-20
    • 2010-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多