1

我想知道 JPA 如何定义来处理以下场景:

Table A: | Table B:
ID  FK_B | ID
1   10   | 10
2   null | 12
3   11   |

我想要所有带有 FK_B NULL 的表 A 条目或引用不可用的表 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)

非常感谢!

4

1 回答 1

1

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 table A for you'd be violating the foreign key constraint.

As far as getting all rows from A where B is null, your first query should work. You can also try:

SELECT a FROM A a WHERE a.b.id IS NULL

although I'm not 100% sure whether that's valid JPA QL syntax (it works for Hibernate)

于 2009-12-03T18:06:04.253 回答