![](/img/trans.png)
[英]hibernate/jpa double OneToOne Bidirectional Relationship to one entity
[英]Wrong insert order at JPA/Hibernate OneToOne bidirectional relationship with the same PK
我正在嘗試在共享相同PK的兩個實體之間建立OneToOne
關系:
+----------------------------------+ +----------------+-----------------+
| Item | | Stats |
+----------------+-----------------+ +----------------+-----------------+
| reference (PK) | other data... | | reference (PK) | other data... |
+----------------+-----------------+ +----------------+-----------------+
| ABCD | ... | | ABCD | ... |
| XYZ | ... | | XYZ | ... |
+----------------+-----------------+ +----------------+-----------------+
其中Stats.reference
是一個FK到Item.reference
:
alter table Stats
add constraint FK_8du3dv2q88ptdvthk8gmsipsk
foreign key (reference)
references Item;
此結構由以下注釋類生成:
@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;
// ...
}
一個新的Item
如下:
Item item = new Item();
item.setReference("ABC");
Stats stats = new Stats();
stats.setItem(item);
item.setStats(stats);
session.save(item);
我的問題是當我執行session.save(item)
INSERT語句順序錯誤時。 Hibernate首先嘗試插入Stats
表而不是Item
,導致FK約束錯誤。
我該如何解決這個問題? 提前致謝。
由於您的類Stats擁有該關聯,請嘗試執行以下操作:
stats.setItem(item);
session.save(stats)
因為你在item和state之間有一對一的關系,而item的stats鍵為FK,這里你的實體對象應該是這樣的
項目{
@OneToOne
@JoinColumn(name = "stat_id", nullable=false) //incase if you allow null
private stats stats
}
在stats實體中不需要添加關系注釋,因為我們在Item中定義了
保存時,您只需保存項目實體,也可以插入統計數據
item.setStats(stats);
session.save(item);
如果你想單獨保存統計數據和單獨保存項目,
那么你已經將級聯類型定義為stats的DETACH
Class Item{
@OneToOne(cascade=CascadeType.DETACH)
@JoinColumn(name = "stat_id", nullable=false) //incase if you allow null
private stats stats
}
Stats
實體中的@JoinColumn
注釋不完整,必須指定屬性referencedColumnName
。
public abstract java.lang.String referencedColumnName
(可選)此外鍵列引用的列的名稱。
@Entity
public class Stats {
@Id
@OneToOne
@JoinColumn(name = "reference", referencedColumnName = "reference")
@Fetch(FetchMode.SELECT)
private Item item;
// ...
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.