Persistence of related objects with same auto-generated key
posted 6 years ago
I'm working on an EJB 3 project using JBoss Server.
My problem concerns persisting related entities with an auto-generated primary key.
I'd like to persist two entities in two tables of an Oracle Database.
They are related unidirectional one-to-one.
Both tables have the same primary key which also forms the link between them.
The primary key should be auto-generated based on a sequence in the database.
What I'm trying to do is to create object one, then (if necessary) object two and then persist both in one step.
To do so, I have a reference to class two in class one and it is annotated "@OneToOne(cascade=CascadeType.ALL)@PrimaryKeyJoinColumn"
I want both objects to be persisted with the same primary key.
This does not work.
Only object one gets the primary key, the primary key of object two is still 0.
The same occurs when I make the relationship bi-directional one-to-one.
I also tried to manually set the primary key of object two but it won't work either as it is not yet set in object one when I need it.
The only idea I still have is not to use auto-generated keys but to manually ask the Oracle-sequence for the next value and then set it in both objects.
But is this really necessary?
I'm sure anyone has encountered this challenge before but I haven't found it on the forum.
Can you help?