Hibernate 条件:如果其子项的任何子项具有特定 属性,则查找实体

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

我需要编写一个条件(或 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=="something" 并且如果 A 具有条件 someProperty=="somethingelse".

我想获取 A 记录的列表

如何为此编写休眠条件?到目前为止我能写的就是以下内容:

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"));

然后我放弃了

如果使用 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();

您需要在 B class 中定义 "private A a;" link。

试试这个

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");