Avoid unnecessary updates when cascading the deletes

Description

Consider this mapping:

<class name="Category" table="category">
<id name="id"><generator class="native"/></id>
<version name="version"/>
<property name="description" not-null="true" column="description"/>
<many-to-one name="parent" column="parent_id" cascade="persist"/>
<set name="children" inverse="true" cascade="all">
<key column="parent_id"/>
<one-to-many class="Category"/>
</set>
</class>

Now suppose we have a root category with some children
and try to delete one of them:

Category root = ... ;

Category child = root.children().iterator().next();
root.remove(child);
session.delete(child);
session.flush();

Hibernate issues these SQL statements:

  • an update for the root entity incrementing the version
    that's ok because the set of children has changed

  • an unnecessary update for the child entity to be deleted
    this update changes no fields (even version) and IMO is unnecessary

  • the deletes for the chilren of deleted child

That unnecessary update is executed even when deleted child has no children.
Its children collection is changed from empty set to null
and that is detected as property change, hence the update.

A better strategy would be not to update entities that are going to be
deleted during the flush.

Environment

None

Assignee

Unassigned

Reporter

tHE DPR

Fix versions

None

Labels

None

backPortable

None

Suitable for new contributors

None

Requires Release Note

None

Pull Request

None

backportDecision

None

Components

Affects versions

Priority

Major
Configure