Jan 20

At work we had a problem with randomly getting the org.hibernate.AssertionFailure: collection was not processed by flush exception thrown in various places.  After searching for a solution we finally found a blog that mentioned a similar issue and a working solution.

Our base model class had an overridden equals() method and hashCode() method that was causing the problem.  If you have overridden a method used for comparison in collections, such as equals(), hashCode(), compare(), be wary that your method is not causing hibernate to instantiate lazily loaded objects during flush.  We had a complex equals() method that used reflection to compare values within a model.  This is bad practice and the equals method should be overridden to check attributes that form a natural key for the object.  For performance as well as resolving this problem we changed our equals method to do the following:

  1. Check if the objects were the same: obj == otherObj
  2. Check if the objects’ surrogate keys were equal: obj.getId() == otherObj.getId() — or obj.getId().equals(otherObj.getId()), depending on your Id datatype
  3. Check if the objects’ natural/business keys were equal: obj.getSSN().equals(otherObj.getSSN())
Those are just examples and show how we fixed the issue.  The main point is that you should reevaluate your equals, hashCode, and comparator methods to determine if that is causing the flush problem.  Hibernate actually has reasoning and best practices for overriding them that you can follow here.

Credit on my team goes to Reddy Kasireddy, and to the blog where he found it:
http://www.jroller.com/jshingler/entry/org_hibernate_assertionfailure_collection_was