我需要编写一个Criteria(或hql)来通过子实体的子属性查找父实体。这是我的实体:
// 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..
}
问题如下。如果任何D记录的条件为importantAttribute ==&#34;那么&#34;我希望获得A
记录列表如果A有条件someProperty ==&#34; somethingelse&#34;。
如何为此编写休眠标准?我所能写的所有内容如下:
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"));
然后我放弃了。
答案 0 :(得分:9)
试试这个
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");
答案 1 :(得分:0)
如果使用HQL,这样的事情应该有效:
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();
您需要拥有&#34;私人A a;&#34; B类中定义的链接。