1

I have the following tables: 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?

Gustavo
  • 1,332
  • 2
  • 16
  • 39
  • Just Read More @ http://java.dzone.com/articles/hibernate-facts-favoring-sets – Amogh Aug 01 '14 at 04:17
  • I don't get it. The article is about relationship between entities in a bidirectional way and problems with duplicates when merging. The case I presented is much more simpler, because there is only one entity. – Gustavo Aug 01 '14 at 10:16

0 Answers0