Incorrect insertion order in unidirectional JPA / Hibernate OneToOne communication with the same PK

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.

+4
source share
3 answers

Since your cool statistics belong to the association, try to do:

stats.setItem(item);
session.save(stats)
+4

, FK, :

{

@OneToOne
@JoinColumn(name = "stat_id", nullable=false) //incase if you allow null
private stats stats

}

, Item

, , ​​

item.setStats(stats);
session.save(item);

,

DETACH

 Class Item{

    @OneToOne(cascade=CascadeType.DETACH)
    @JoinColumn(name = "stat_id", nullable=false) //incase if you allow null
    private stats stats
}
0

@JoinColumnthe annotation in Statsessence is not complete, the attribute referencedColumnNamemust be specified.

public abstract java.lang.String referencedColumnName

(optional) The name of the column referenced by this foreign key column.

@Entity
public class Stats {

   @Id
   @OneToOne
   @JoinColumn(name = "reference", referencedColumnName = "reference")
   @Fetch(FetchMode.SELECT)   
   private Item item;  

   // ...
}
0
source

All Articles