Monday, June 22, 2009

Hibernate cascade save-update issues

Using "save-update" has some potential performance issues. For example, consider:

<hibernate-mapping>
<class name="org.ikangaroo.nestegg.entities.AssetTracker" table="ASSET_TRACKER">
<id name="id" column="ASSET_TRACKER_ID">
<generator class="increment" />
</id>

<map name="trackedAssets" table="TRACKED_ASSETS" lazy="false" cascade="save-update">
<key column="ASSET_TRACKER_ID" />
<map-key type="integer" column="ASSETS_YEAR"/>
<one-to-many class="org.ikangaroo.nestegg.entities.Assets"/>
</map>

</class>

</hibernate-mapping>

Here TrackedAssets contains a collection (Map) of Assets.

Suppose, TrackedAssets contains 10 Assets. Now I add a 11th one. And I do session.update(trackedAssets). This will cause Hibernate to generate 11 database queries to update all the 11 Assets. This is not very efficient, since the 10 have not changed at all.

As you can see, if there were 100 entries and you add 1 new one - that will cause 101 database queries!!!

I personally think it is better to not use save-update through cascade. Instead, do the save-update yourself as required in your code. That way you can do incremental updates, instead of making hibernate do full updates which are expensive.

Note that "delete" option of cascade is quite alright to use.

No comments:

Post a Comment