I have the following tables:
The following classes:
public class Parent {
private int id;
private Set<Child> children;
// getters and setters
}
public class Child {
private int id;
private String attr;
// getters and setters
public int hashCode() {
return this.getId();
}
public boolean equals(Object obj) {
return obj instanceof Child && this.getId() == ((Child)obj).getId();
}
}
And the following Hibernate mapping:
<class name="Parent" table="parent">
<id name="id" column="id"/>
<set name="children" table="child">
<key column="id_parent"/>
<composite-element class="Child">
<property name="id" column="id"/>
<property name="attr" column="attr"/>
</composite-element>
</set>
</class>
Whenever I change attr
attribute from a Child
or add/remove a Child
to/from the collection and commit the transaction, the entire collection is deleted and the remaining children are reinserted with the new attribute values.
Other topics discuss this, and the guys always blame equals()
and hashCode()
or the fact the collection is a list or bag. But in this very simple case I don't think they are the problem.
Is this because I'm using an entity (Parent
) and a component class (Child
) instead of using two entities in a one-to-many relationship?