【问题标题】:Add new Entity to persisted Collection将新实体添加到持久集合
【发布时间】:2010-01-22 09:54:56
【问题描述】:

我有一对多关联中的相关表:产品*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);
    }
}

-

@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;
    }
}

我有以下情况:

  1. 我保留了一个带有空库存集的产品
  2. 我加载了这个产品
  3. 我向产品添加库存
  4. 我尝试更新/合并产品

这样做,我得到以下异常:

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

【问题讨论】:

  • 如果根本不添加库存会发生这种情况吗?
  • 不,没有新的库存保存工作正常

标签: java database hibernate orm


【解决方案1】:

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

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

【讨论】:

  • merge() on Inventory 给了我同样的例外!我会尝试覆盖 hashcode() 和 equals()
猜你喜欢
  • 2015-11-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-09-29
  • 1970-01-01
相关资源
最近更新 更多