views:

292

answers:

1

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!

+1  A: 

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)

ChssPly76
Thanks a lot! It works fine...
marabol
I must learn, that this statemant only works with hibernate, but not with toplink ;-)For your statement toplink generate this SQL statement:SELECT t0.ID, t0.FK_B FROM A t0, B t1 WHERE (t1.ID IS NULL) AND (t1.ID = t0.FK_B)THis works fine with both hibernate and toplink:SELECT a FROM A a WHERE a.b IS NULLThan toplink build this statement:SELECT t0.ID, t0.FK_B FROM A t0 WHERE (t0.FK_B IS NULL)
marabol