简体   繁体   中英

Add new Entity to persisted Collection

I've got to Tables related in one-to-many association: 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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