A little trick with insert order that might be interesting to some. Inserts are normally done in the order that objects are added to the persistence context. However, cascading can "promote" an insertion to earlier than you might think.
Say I have:
A --> C
B --> C
Where --> is a cascading one-to-many relationship. C is obviously a join table.
Then I do:
add A
add B
add C to both A and B
The inserts do NOT happen in this order:
A
B
C
What really happens is:
insert A (and cascade to C)
insert B (and cascade to C - but find we don't need to)
insert C (Oh, don't need to)
so the real order is:
A
C
B
If B --> C is not nullable, this will crash on the second insert.
To get around this, do either:
add A
add B
flush
add C to both A and B
or:
add B
add A
add C to both A and B
or even (not sure why this works):
add A
add B
add C to both A and B
session.save(B)
Kinda obvious when you think about it - not obvious when you don't!
|