如何处理具有可用外键条目但不可用外键条目的 JPA JOIN?
我想知道 JPA 如何定义来处理以下情况:
Table A: | Table B:
ID FK_B | ID
1 10 | 10
2 null | 12
3 11 |
我希望所有表 A 条目的 FK_B 为 NULL 或引用不可用的表 B 条目。
public class A implements Serializable {
@Id
private Long id;
@JoinColumn(name = "FK_B", nullable = true)
@ManyToOne
private B b;
}
public class B implements Serializable {
@Id
private Long id;
}
它是否已定义,如果我使用
SELECT a FROM A a LEFT JOIN a.b WHERE a.b IS NULL
或会发生什么:(这可能吗?)
SELECT a FROM A a LEFT JOIN B b on (b = a.b) WHERE b IS NULL
我需要的是一个包含
A(id = 2)
A(id = 3)
非常感谢!
I wonder how JPA defines to handle following scenario:
Table A: | Table B:
ID FK_B | ID
1 10 | 10
2 null | 12
3 11 |
I want all Table A entries with FK_B NULL or referencing not available Table B entry.
public class A implements Serializable {
@Id
private Long id;
@JoinColumn(name = "FK_B", nullable = true)
@ManyToOne
private B b;
}
public class B implements Serializable {
@Id
private Long id;
}
Is it defined, what happens if I use
SELECT a FROM A a LEFT JOIN a.b WHERE a.b IS NULL
or: (Is this possible?)
SELECT a FROM A a LEFT JOIN B b on (b = a.b) WHERE b IS NULL
What I need is a list containing
A(id = 2)
A(id = 3)
Thanks a lot!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
根据定义,表 A 中的第 3 行是非法的;如果没有 ID=11 的
B
,则表A
中不能包含该行,因为这会违反外键约束。至于从
A
获取所有行(其中B
为 null),您的第一个查询应该可以工作。您也可以尝试:虽然我不能 100% 确定这是否是有效的 JPA QL 语法(它适用于 Hibernate)
Row #3 in your Table A is illegal by definition; if there's no
B
with ID=11 you can't have that row in tableA
for you'd be violating the foreign key constraint.As far as getting all rows from
A
whereB
is null, your first query should work. You can also try:although I'm not 100% sure whether that's valid JPA QL syntax (it works for Hibernate)