[英]Add new Entity to persisted Collection
我已經了解到一對多關聯中的表:Product * 1-n * Inventory
@Entity
public class Product {
// Identifier and properties ...
@OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
public Set<Inventory> getInventories() {
return inventories;
}
public void setInventories(Set<Inventory> inventories) {
this.inventories = inventories;
}
public void addInventory(Inventory inventory) {
this.inventories.add(inventory);
inventory.setProduct(this);
}
}
-
@Entity
public class Inventory {
// Identifier and properties ...
private Product product;
@ManyToOne(cascade = CascadeType.ALL, optional = false)
public Product getProduct() {
return product;
}
public void setProduct(Product product) {
this.product = product;
}
}
我有以下情況:
這樣做,我得到以下啟示:
HibernateSystemException: a different object with the same identifier value was already associated with the session
異常意味着會話中存在一個與@Id
列具有相同值的對象,並且該對象與當前對象不同。
您必須重寫Inventory
上的hashCode()
和equals()
(最好使用業務密鑰),即使對象實例不同,會話也可以通過該方法知道這是同一實體。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.