I'm trying to set up a OneToOne relationship between two entities that share the same PK:
+----------------------------------+   +----------------+-----------------+        
|              Item                |   |              Stats               |
+----------------+-----------------+   +----------------+-----------------+
| reference (PK) |  other data...  |   | reference (PK) |  other data...  |
+----------------+-----------------+   +----------------+-----------------+
|          ABCD  |      ...        |   |          ABCD  |      ...        |
|           XYZ  |      ...        |   |           XYZ  |      ...        |
+----------------+-----------------+   +----------------+-----------------+
where Stats.reference is a FK to Item.reference:
alter table Stats 
    add constraint FK_8du3dv2q88ptdvthk8gmsipsk 
    foreign key (reference) 
    references Item;
This structure is generated from the following annotaded 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;  
   // ...
}
A new Item is creted as follows:
Item item = new Item();
item.setReference("ABC");
Stats stats = new Stats();
stats.setItem(item);
item.setStats(stats);
session.save(item);
My problem is when I do session.save(item) the INSERT statements order are wrong. 
Hibernate first tries to insert into Stats table instead of Item, resulting in a FK constraint error. 
How can I solve this issue? Thanks in advance.
Since your class Stats owns the association, try to do :
stats.setItem(item);
session.save(stats)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With