繁体   English   中英

将新实体添加到持久集合

[英]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;
    }
}

我有以下情况:

  1. 我坚持使用空库存集的产品
  2. 我加载这个产品
  3. 我向产品添加库存
  4. 我尝试更新/合并产品

这样做,我得到以下启示:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM