我有parent:child继承模型:
@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 [???]
。我尝试写child
,Child
无济于事。
还是有其他方法可以实现同一目标?
不能选择JPA CriteriaQuery Join - how to join on a subelement?解决方案。
答案 0 :(得分:0)
我最终使用了子查询:
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));
注意:很显然,如果有机会,请使用上述链接中建议的组成。