jpa-2.0 - 使用连接继承表时连接子表 [谓词]
问题描述
我有父:子继承模型:
@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 -如何加入子元素?解决方案不是一种选择。
解决方案
我最终使用了一个子查询:
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));
注意:显然,如果您有机会,请使用上述链接中建议的组合。
推荐阅读
- html - 箱形阴影未显示
- c - 使用递归找到用户定义矩阵的行列式
- java - 创建叶病检测安卓应用程序的第一个过程是什么?
- php - 找到相同的输入数据并将其替换为新数据,然后再将其写入 txt 输出
- c++ - 如何使用一个 std::thread 对象来运行 2 个顺序事件(函数)?
- regex - 正则表达式匹配表达式以获取两个分隔符之间的单词(有或没有值)
- c# - 调用 UserDeletingRow 事件并回答“否”后,行从网格视图中消失,如果我想删除它
- php - 在 JSON 响应 PHP 中列出值
- youtube-api - 如何向 YouTube API CommentThreads:list 查询的 searchTerms 参数添加多个值?
- ios - 当我无法使用本地存储时,我必须如何处理 apollo-client 的解析器?