Define hashCode() and equals()

From Shrubbery

Revision as of 12:22, 7 May 2007 by Josh (Talk | contribs)
Jump to: navigation, search


One of the most common problems that I've seen developers make with Hibernate and JPA is not defining hashCode() and equals() on entity/embeddable element classes that are used in one-to-many associations. People seem to forget that just because they are using Hibernate doesn't mean that you also don't have to make well behaved Java objects! In fact, every book on Hibernate that I know of takes people through examples where the authors first make a well behaved Java object and then add persistence.

Here are the typical problems that happen when hashCode() and equals() have not been defined properly:

  1. Duplicate 'child' objects are inserted into the database.
  2. Unique constraints get violated causing transactions to be rolled back.

There is nothing wrong with Hibernate in these cases! It is just doing what you asked it to do (which is nonsense)!

Here are the rules, all spelled out:

  • Any object that is used in a persistent collection should define hashCode() and equals().
  • The definitions of hashCode() and equals() should be consistent. That is, two objects with the same hash may or may not be equal, and two objects that are equal must have the same hash.
  • The definitions of hashCode() and equals() should never use the generated ID (surrogate key)! Instead, use the business key of the object. See Business Key vs. Surrogate Key
Personal tools