问题
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.
回答1:
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");
回答2:
If using HQL, something like this should work:
TypedQuery<A> query = em .createQuery( "SELECT a FROM D d join fetch d.c c join fetch c.b b join fetch b.a a where a.someProperty = :someProperty and d. importantAttribute = :importantAttribute", A.class); query.setParameter("someProperty", "somethingelse"); query.setParameter("importantAttribute", "something"); List<A> results = query.getResultList();
You'd need to have a "private A a;" link defined in your B class.
来源:https://stackoverflow.com/questions/29436261/hibernate-criteria-find-entity-if-any-of-its-childrens-children-have-a-specifi