我得到了一对多关联中的表: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
答案 0 :(得分:2)
该异常意味着会话中存在具有相同@Id
列值的对象,该对象与当前对象不同。
您必须覆盖hashCode()
上的equals()
和Inventory
(最好使用业务键)会话才能知道这是同一个实体,即使对象实例是不同。