Hello everyone,
I've been trying to work through a problem today and I can't seem to find the solution. I searched the forum, but was unable to find the same issue (which tells me I'm probably doing something wrong).
Either way, here's an explanation:
I have three Objects.
Object1, Object2, Object3
Object1 has a one-to-many relationship w/ Object2
Object2 has a one-to-one relationship w/ Object3
I'm using JPA/Hibernate annotations and my classes are setup accordingly:
Code:
@Entity
public class Object1 {
@Id
@column(...)
private int object1Id;
@OneToMany(
targetEntity=Object2
cascade={CascadeType.PERSIST, CascadeType.MERGE},
fetch=FetchType.LAZY
)
@JoinColumn(name="Object1Id" referencedColumn="Object1Id")
private List Object2List;
}
@Entity
public class Object2 {
@Id
@column(...)
private int object2Id;
@column(...)
private int object1Id;
@OneToOne(
targetEntity=Object3
cascade={CascadeType.PERSIST, CascadeType.MERGE},
fetch=FetchType.LAZY
)
@JoinColumn(name="Object2Id" referencedColumn="Object2Id")
private Object3 object3;
}
@Entity
public class Object3 {
@Id
@column(...)
private int object3Id;
@column(...)
private int object2Id;
}
When I go to persist a new Object1 (EntityManager.persist) everything gets written to the database (Object 1, 2, and 3). The relationship between Object1 & Object2 is perfect, but the relationship between Object2 and Object3 is not kept intact.
What I mean is: Object3.object2Id is never populated w/ the sequence derived during the call to persist...it always ends up being 0.
By looking at the Hibernate SQL log, I can see that the following is happening:
1. Since each object has it's own sequence based id, Hibernate is getting a new id for each object.
2. 3 inserts are run, one for each of the new objects.
3. Hibernate executes an update on the table related to Object2 (updating the Object2.object1Id column so that it's properly tied to the new Object1 entry).
...and that's all it does. The object2Id is never updated on the Object3 table.
Is my OneToOne annotation incorrect??
Thanks in advance,
-m