首页 > 解决方案 > 使用连接继承表时连接子表 [谓词]

问题描述

我有父:子继承模型:

@Entity
@Table(name = "PARENT")
@Inheritance(strategy = InheritanceType.JOINED)
public class Parent {
  ...
  id
}

@Entity
@Table(name = "CHILD")
public class Child extends Parent {
   ... 
   @OneToMany(mappedBy = "id", orphanRemoval = true, fetch = FetchType.LAZY, cascade = CascadeType.ALL)
   private Set<Foo> foos = new HashSet<>();
}

如何使用 加入这两个表Predicates?前提是根是Root<Parent>。默认情况下,这已经由 JPA 完成,但我需要在这两者之间进行连接对象访问以进一步加入Foo列表。

CriteriaQuery<Parent> q = cb.createQuery(Parent.class);
Root<Parent> r = q.from(Parent.class);

Join<Parent, Child> cJoin = r.join("???", JoinType.LEFT);  <-- ERROR
cJoin.on(cb.equal(r.get("id"), cJoin.get("id")));

Join<Child, Foo> fJoin = cJoin.join("foos", JoinType.LEFT);
fJoin.on(cb.equal(r.get("id"), cJoin.get("id")));

不知道子表名怎么表达,见"???"代码示例中的。这产生Unable to locate Attribute with the the given name [???]. 我试过写childChild无济于事。

或者有没有其他方法可以达到同样的目的?

JPA CriteriaQuery Join -如何加入子元素?解决方案不是一种选择。

标签: jpa-2.0predicate

解决方案


我最终使用了一个子查询:

CriteriaQuery<Parent> q = cb.createQuery(Parent.class);
Root<Parent> r = q.from(Parent.class);

Subquery<Long> childSubQuery = q.subquery(Long.class);
Root<Child> childRoot = childSubQuery.from(Child.class);
Join<Child, Foo> fJoin = childRoot.join("foos", JoinType.LEFT);
fJoin.on(cb.equal(childRoot.get("id"), fJoin.get("id")));
childSubQuery.select(childRoot.get("id"));
childSubQuery.where(cb.equal(fJoin.get("condition"), conditionValue));

q.where(cb.equal(r.get("id"), childSubQuery));

注意:显然,如果您有机会,请使用上述链接中建议的组合。


推荐阅读