[英]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.