简体   繁体   English

将新实体添加到持久集合

[英]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: 我有以下情况:

  1. I persist a Product with empty Inventory Set 我坚持使用空库存集的产品
  2. I load this Product 我加载这个产品
  3. I add an Inventory to Product 我向产品添加库存
  4. I try to update/merge Product 我尝试更新/合并产品

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.

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