Hibernate 中的嵌套 createAlias()

Nested createAlias() in Hibernate

我必须使用 Hibernate 进行特定查询。

下面的class只是一个简单的例子,让你更容易理解我的场景和我的目标。我在写这个post时编造了例子,希望我没有出错(反正不要注意错误:D)。

class Father{
  int id;

  @OneToMany(mappedBy = "father", fetch = FetchType.LAZY)
  List<Son> sonList;
}

class Son{
 @ManyToOne(targetEntity=Father.class)  
 @JoinColumn(referencedColumnName = "id", name = "father")
 Father father;

 @OneToMany(mappedBy = "son", fetch = FetchType.LAZY)
 List<Toy> toyList;
}

class Toy{
 @ManyToOne(targetEntity=Son.class) 
 @JoinColumn(referencedColumnName = "id", name = "son")
 Son son;

 @OneToMany(mappedBy = "Feature", fetch = FetchType.LAZY)
 List<Feature> featureList;
}

class Feature{
 @ManyToOne(targetEntity=Toy.class)
 @JoinColumn(referencedColumnName = "id", name = "toy") 
 Toy toy;

 boolean unisex;
}

我必须 select 从数据库 Fatherid = 1,和他的亲戚 Son,但只有儿子 Toy Feature.unisex = true.

我不知道如何到达 class Toy 的字段 Feature.unisex

有了createAlias()我可以做到:

Criteria criteria = session.createCriteria(Father.class);           
criteria.createAlias("sonList", "sonListAlias");
criteria.add(Restrictions.idEq(1));
criteria.add(Restrictions.in("sonListAlias.toyList", toyList));

但我不能更进一步。我应该需要这样的东西:

Criteria criteria = session.createCriteria(Father.class);           
criteria.createAlias("sonList", "sonListAlias");
criteria.add(Restrictions.in("sonListAlias.toyList.featureList.unisex", unisex));

但是,当然,这不是正确的方法。

提前谢谢你。

首先,请不要使用不必要的映射属性。我的意思是 targetEntity=Father.classreferencedColumnName = "id", name = "father"。并且不要使用 sonList 这样的名称,只需 sons.

Criteria criteria = session.createCriteria(Father.class);           
criteria.createAlias("sonList", "son");
criteria.createAlias("son.toyList", "toy");
criteria.createAlias("toy.featureList", "feature");
criteria.add(Restrictions.idEq(1));
criteria.add(Restrictions.eq("feature.unisex", true));

如果需要急切获取sonList,可以尝试使用setFetchMode("sonList", FetchMode.JOIN).

如果你需要

"always" get a father and get only his sons that have toys that have Feature.unisex = true

你可以尝试使用@Filter

Hibernate @Filter and @FilterJoinTable Annotation Example

但我认为如果您在单独的请求中加载 sonList 会更好

    Criteria criteria = session.createCriteria(Son.class);           
    criteria.createAlias("father", "father");
    criteria.createAlias("toyList", "toy");
    criteria.createAlias("toy.featureList", "feature");
    criteria.add(Restrictions.eq("father.id", 1));
    criteria.add(Restrictions.eq("feature.unisex", true));