Flushing and clearing the Hibernate session

I am working on a largish application and was faced with a couple of Hibernate related problems.

– Hibernate reporting that deleted entities will be saved again because they are included in other entities.
– Persisted entities for which the key remains null.

Both were fixed by inserting a flushAndClear() on the Hibernate session in the right place. This however introduces a few new problems.

– A need to refetch data from the database as all attached entities are detached by the flushAndClear().
– Hibernate complaining about an identity being added in the session while another entity with same type and ID already exists.

Time to hunt for the real reasons why the flushAndClear() was needed.

In the end, two problems caused all the troubles.

– When you add an object to a relation (a set or list in an object which is attached to the session) that object will automatically be saved (depending on your cascade settings). However this will not automatically set the generated id on that object. To assure that the object id can be read, you may need to save the object explicitly and only then add it in the relation.

– Bulk updates and deletes should never be done inside an existing Hibernate transaction. Bulk operations do not change the state in the session and this can cause many conflicts. Bulk updates should only be done in separate transactions.

Leave a Reply

Your email address will not be published. Required fields are marked *

question razz sad evil exclaim smile redface biggrin surprised eek confused cool lol mad twisted rolleyes wink idea arrow neutral cry mrgreen