Search code examples
javahibernatelistormhibernate-mapping

Why does Hibernate require the list-index to be nullable?


I have a mapping similar to the following and it seems that the index column is not populated during the DB INSERT statement because the DB complains about index being NULL. However, if I make the index column nullable it works as expected.

<list name="someList">
    <key column="someFk"/>
    <list-index column="index"/>
    <one-to-many class="SomeClass"/>
</list>

Is there a way to force Hibernate to populate the index while inserting? I'm sure there must be a way but I've looked into the docs and couldn't find anything.


Solution

  • This behavior can be explained through the prism of Hibernate flush operation order. If you take a look at the ActionQueue class, you'll see that the entity state transitions are executed in the following order:

    1. OrphanRemovalAction
    2. AbstractEntityInsertAction
    3. EntityUpdateAction
    4. QueuedOperationCollectionAction
    5. CollectionRemoveAction
    6. CollectionUpdateAction
    7. CollectionRecreateAction
    8. EntityDeleteAction

    Now, the SQL INSERT statement is executed by the AbstractEntityInsertAction while the index is assigned through an UPDATE statement by the CollectionRecreateAction.

    While I agree that it would be much more efficient to remove the UPDATE statement and populate the list index on INSERT, I think this change is going to require a considerable amount of refactoring work. You could open a JIRA issue for this, and mark it as an improvement.