Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate Criteria: find entity if any of its children's children have a specific property

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.

like image 265
sedran Avatar asked Jan 09 '23 15:01

sedran


1 Answers

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");
like image 122
Predrag Maric Avatar answered Jan 17 '23 04:01

Predrag Maric