Java 将新实体添加到持久化集合

Java 将新实体添加到持久化集合,java,database,hibernate,orm,Java,Database,Hibernate,Orm,我有一对多关联的表:产品*1-n*库存 @Entity public class Product { // Identifier and properties ... @OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL) public Set<Inventory> getInventories() { return inventories; } p

我有一对多关联的表:产品*1-n*库存

@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);
    }
}
我有以下情况:

  • 我将保留库存集为空的产品
  • 我装这个产品
  • 我将库存添加到产品中
  • 我尝试更新/合并产品
  • 这样做,我得到以下解释:

    HibernateSystemException: a different object with the same identifier value was already associated with the session
    

    异常意味着会话中存在与
    @Id
    列值相同的对象,并且该对象与当前对象不同


    您必须覆盖
    Inventory
    上的
    hashCode()
    equals()
    (最好使用业务密钥),这样即使对象实例不同,会话也会知道这是同一个实体。

    如果您根本不添加库存,是否会发生这种情况?否,没有新的库存保存()在库存上给了我同样的解释!我将尝试重写hashcode()和equals()
    HibernateSystemException: a different object with the same identifier value was already associated with the session