views:

40

answers:

1

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
+1  A: 

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.

Bozho
merge() on Inventory gives me the same Exeption!I'll try to override hashcode() and equals()
woezelmann
yeah it works :D
woezelmann