[英]Add new Entity to persisted Collection
I've got to Tables related in one-to-many association: Product*1 - n*Inventory 我已经了解到一对多关联中的表: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;
}
}
I have following situtation: 我有以下情况:
Doing this, I get following exeption: 这样做,我得到以下启示:
HibernateSystemException: a different object with the same identifier value was already associated with the session
The exception means that an object with the same value of the @Id
column exists in the session, and which isn't the same object as the current one. 异常意味着会话中存在一个与
@Id
列具有相同值的对象,并且该对象与当前对象不同。
You have to override hashCode()
and equals()
on the Inventory
(using a business key preferably) by which the session will know this is the same entity, even if the object instance is different. 您必须重写
Inventory
上的hashCode()
和equals()
(最好使用业务密钥),即使对象实例不同,会话也可以通过该方法知道这是同一实体。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.