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:
- Check if the objects were the same: obj == otherObj
- Check if the objects’ surrogate keys were equal: obj.getId() == otherObj.getId() — or obj.getId().equals(otherObj.getId()), depending on your Id datatype
- Check if the objects’ natural/business keys were equal: obj.getSSN().equals(otherObj.getSSN())
Credit on my team goes to Reddy Kasireddy, and to the blog where he found it: