Hibernate version: 3.0.5
When mapping a bidirectional association using a list (as suggested from the Hibernate Users FAQ), such that the collection-valued end controls the association, Hibernate is supposed (as far as I understand it) to manage the index assignment.
Mapping documents:
(see
http://www.hibernate.org/116.html#A9)
Code:
<hibernate-mapping>
<class name="Parent">
<id name="id">
<generator class="sequence"/>
</id>
<list name="children" lazy="true">
<key column="parent_id" not-null="true"/>
<list-index column="child_order"/>
<one-to-many class="Child"/>
</list>
</class>
<class name="Child">
<id name="id">
<generator class="sequence"/>
</id>
<property name="name"/>
<many-to-one name="parent" class="Parent"
column="parent_id" not-null="true"
insert="false" update="false"/>
</class>
</hibernate-mapping>
Practically, there are some, uhhh, "missing features" with this approach. Maybe I did something wrong, maybe I expected something that Hibernate can't deliver, or maybe Hibernate could (althogh almost perfect ;-)) be improved regarding the following issues:
1)
Hibernate does not take the base-attribute of the list-index element into account:
Say you are mapping the children list like this:
Code:
<list name="children" lazy="true">
<key column="parent_id" not-null="true"/>
<list-index column="child_order" base="1"/>
<one-to-many class="Child"/>
</list>
If you are adding an element to such a list, Hibernate automatically assigns a new index for it, but misses to increment the index by [base]:
If you have children 1,2,3,4 and add a new child, Hibernate assigns "4" to the new element, resulting in the indexes 1,2,3,4,4. When reading the list from the DB, one child with index 4 wins over the other with index 4, resulting in a list of four elements only (instead of five).
2)
Hibernate does not automatically renumber list indexes, when elements are deleted from the middle of the list:
If you have children 0,1,2,3,4 and delete child 2, the list ends up with indexes 0,1,3,4. When reading this list from the DB again, it yields:
Child 0, Child 1, null, Child 3, Child 4. This is certainly not desireable.
Please note: When mapping the association in the suggested way, the column "child_order" can't be mapped explicitly to your java class. This means, there is no way to manually renumber the list.
If you ever want to delete elements from the list, you must use the Hibernate 2 approach (mapping the list with inverse="true" and manually keep care of your list indexes which is always possible, but somewhat clumsy).
Any thoughts on these issues? Are these two points supposed to work? Did I something wrong? Do I have wrong expectations? Are these missing features?