Hibernate criteria query on different properties of different objects

后端 未结 3 773
谎友^
谎友^ 2021-02-01 07:41

Suppose I have classes like:

class A {
 B getB();
 C getC();
}

class B {
 String getFoo();
}

class C {
 int getBar();
}

and I want to filter

相关标签:
3条回答
  • 2021-02-01 08:09

    Use aliases instead of nested criteria:

    Criteria criteria = session.createCriteria(A.class)
     .createAlias("b", "b_alias")
     .createAlias("c", "c_alias")
     .add(Restrictions.disjunction()
      .add(Restrictions.eq("b_alias.foo", "Something"))
      .add(Restrictions.eq("c_alias.bar", "0"))
     );
    
    0 讨论(0)
  • 2021-02-01 08:09

    In case someone else finds it useful, I found a more complicated answer to the problem which appears to be allowed by the API, though I did not get to test it before ChssPly posted his (simpler) solution:

    DetachedCriteria bValues = DetachedCriteria.forClass(A.class);
    bValues.createCriteria("b").add(Restrictions.eq("foo", "something"));
    
    DetachedCriteria cValues = DetachedCriteria.forClass(A.class);
    cValues.createCriteria("c").add(Restrictions.eq("bar", 0));
    
    Restrictions.or(Subqueries.in("id", bValues), Subqueries.in("id", cValues));
    
    0 讨论(0)
  • 2021-02-01 08:15

    You only need to create one criteria object like so.

    Criteria criteria = session.createCriteria(A.class);
    criteria.add(Restriction.disjunction()
        .add(Restriction.eq("b.foo", "something"))
        .add(Restriction.eq("c.bar", 0)));
    
    0 讨论(0)
提交回复
热议问题