I am trying to configure communication OneToOnebetween two objects that use the same PK:
+----------------------------------+ +----------------+-----------------+
| Item | | Stats |
+----------------+-----------------+ +----------------+-----------------+
| reference (PK) | other data... | | reference (PK) | other data... |
+----------------+-----------------+ +----------------+-----------------+
| ABCD | ... | | ABCD | ... |
| XYZ | ... | | XYZ | ... |
+----------------+-----------------+ +----------------+-----------------+
where Stats.referenceis FK before Item.reference:
alter table Stats
add constraint FK_8du3dv2q88ptdvthk8gmsipsk
foreign key (reference)
references Item;
This structure is created from the following annotated classes:
@Entity
public class Item {
@Id
private String reference;
@OneToOne(mappedBy = "item", optional = false)
@Cascade({CascadeType.SAVE_UPDATE})
@Fetch(FetchMode.SELECT)
private Stats stats;
}
@Entity
public class Stats {
@Id
@OneToOne
@JoinColumn(name = "reference")
@Fetch(FetchMode.SELECT)
private Item item;
}
The new one is Itemas follows:
Item item = new Item();
item.setReference("ABC");
Stats stats = new Stats();
stats.setItem(item);
item.setStats(stats);
session.save(item);
My problem is that I am making the session.save(item)order of the INSERT statements wrong. Hibernate first tries to insert into the table Statsinstead Item, which will result in an FK constraint error.
How can I solve this problem? Thanks in advance.
source
share