concept equals() in category hibernate

appears as: equals()
Java Persistence with Hibernate, Second Edition

This is an excerpt from Manning's book Java Persistence with Hibernate, Second Edition.

  • Instance equality, as determined by the implementation of the equals() method (also called equality by value)
  • On the other hand, the identity of a database row is expressed as a comparison of primary key values. As you’ll see in section 10.1.2, neither equals() nor == is always equivalent to a comparison of primary key values. It’s common for several non-identical instances in Java to simultaneously represent the same row of the database—for example, in concurrently running application threads. Furthermore, some subtle difficulties are involved in implementing equals() correctly for a persistent class and understanding when this might be necessary.

    Let’s say you keep several Image instances in a HashSet. You know that sets don’t allow duplicate elements. How do sets detect duplicates? The HashSet calls the equals() method on each Image you put in the Set. (It also calls the hashCode() method to get a hash, obviously.) How many images are in the following collection?

    For the Image class, you don’t rely on Java identity—you override the equals() and hashCode() methods.

    Listing 7.11. Implementing custom equality with equals() and hashCode()