Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wrong insert order at JPA/Hibernate OneToOne bidirectional relationship with the same PK

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.

like image 632
Tobías Avatar asked Sep 27 '22 08:09

Tobías


1 Answers

Since your class Stats owns the association, try to do :

stats.setItem(item);
session.save(stats)
like image 92
Bilal BBB Avatar answered Oct 13 '22 02:10

Bilal BBB