Friday, November 14, 2014

hashCode() vs. equals() vs. Hibernate: Are These Two Persons Exact Twins?

Basics:
  • In general, even when using Hibernate or other ORM, don't have to overwrite the Object's hashCode() and equals().
  • However, you need to do it if both conditions below are true in your case:
    • you use dettach() with later reAttach(), and
    • you use your identity in Sets
  • Hibernate uses equals() (and/or hashCode() ?) only to tell that two objects represent the same entity and not whether it's values have changed (it iterates over the attributes for this purpose).
  • If you use entities in a Set, never change any component of the hashCode() while the object is in the Set. The best way is to make the business key immutable.
  • For overwriting hashCode()/equals(), you can use EqualsBuilder and HashCodeBuilder from the Apache Commons Lang library. Or semit-auto generate them both, always both of them, using eclipse.
 So, to tell whether the data is different/same between two objects, don't use hashCode() nor equals(), but create another method.

No comments: