开发者

Add new Entity to persisted Collection

开发者 https://www.devze.com 2022-12-17 14:22 出处:网络
I\'ve got to Tables related in one-to-many association: Product*1 - n*Inventory @Entity public class Product {

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:

开发者_StackOverflow社区
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.

0

精彩评论

暂无评论...
验证码 换一张
取 消