I have the following use case:
A hierarchical, tree like organization structure where each organization is a parent of zero or more organizations. The children organizations are ordered.
this is implemented with the following table in the database:
table Organization (
id int not null, /* primary key, autoincrement */
parentId int null, /* can be null if the organization is at topmost level*/
position int null /* position of the organization in the children list */
)
This is the mapping I'm trying to use (omited the not relevant parts)
<many-to-one name="parent" class="Organization" not-null="false" update="false" insert="false">
<column name="parentId"/>
</many-to-one>
<list name="children" cascade="all,delete-orphan">
<key not-null="true"> <!-- note not-null here!!! -->
<column name="parentId"/>
</key>
<list-index>
<column name="position"/>
</list-index>
<one-to-many class="Organization" />
</list>
The problem with this is that because the key of the list is specified as not-null, adding a new organization at top level fails (as it doesn't have a parent)
If the key of the list is specified as not-null="false" then hibernate doesn't update the parent reference nor the position in the list. That is caused by this check in the org.hibernate.cfg.HbmBinder:
if ( collection.isOneToMany()
&& !collection.isInverse()
&& !collection.getKey().isNullable() /* <-- this is the check that forces the use of not-null="true" */) {
My question is:
Am I missing something, or this is really a functional limitation of Hibernate?
I know that there are some workarounds for this problem, but I'm interested in a clean, configuration based solution.
|