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

孤街浪徒 提交于 2019-12-10 15:44:01

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!