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:
- I persist a Product with empty Inventory Set
- I load this Product
- I add an Inventory to Product
- 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.
精彩评论