I need to write a Criteria(or hql) to find a parent entity by a property of a child of its children entities. Here is my entities:
// The top level parent class
public class A {
private Long id;
private String someProperty;
private B b;
// and some other attributes...
}
// The second level parent class :)
public class B {
private Long id;
private List<C> cList;
// and some other attributes...
}
public class C {
private Long id;
private B b;
private List<D> dList;
// Other attributes..
}
public class D {
private Long id;
private C c;
private String importantAttribute;
// Other attributes..
}
The question is the following. I want to get the list of A
records if any of D records have the condition importantAttribute=="something" and if A have the condition someProperty=="somethingelse".
How can I write a hibernate criteria for this? All I could write until now is the following:
Criteria criteria = getSession().createCriteria(A.class, "a");
criteria.add(Restrictions.eq("a.someProperty", "somethingelse");
DetachedCriteria sub = DetachedCriteria.forClass(D.class, "d");
sub.add(Restrictions.eq("d.importantAttribute", "something"));
sub.setProjection(Projections.property("id"));
Then I gave up.
Try this
Criteria criteria = getSession().createCriteria(A.class, "a");
criteria.createAlias("a.b", "b");
criteria.createAlias("b.cList", "c");
criteria.createAlias("c.dList", "d");
criteria.add(Restrictions.eq("a.someProperty", "somethingelse");
criteria.add(Restrictions.eq("d.importantAttribute", "something");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With