This article is participating in “Java Theme Month – Java Debug Notes Event”, see < Event link > for more details.

Question: About JPA’s hashCode ()/equals () dilemma

There has been some discussion here about JPA entities and which JPA entity classes should be implemented using hashCode()/ equals(). Most of them rely on Hibernate, but I want to discuss how they are self-implementing (I’m using EclipseLink, by the way).

All possible implementations have advantages and disadvantages in the following areas:

1, invariance of hashCode()/ equals() operations on List and Set.

2. The same objects can be detected (e.g., dynamic proxies from lazy-loaded data structures from different sessions)

3. Whether the entity behaves correctly in its subordinate (or non-persistent) state

In my opinion, there are three operations:

Don’t cover them; Rely on object.equals () and object.hashcode ()

  • The hashCode ()/the equals () work
  • Unable to identify the same object, dynamic proxy problem
  • Independent entities are fine

Override them by primary key

  • HashCode ()/equals() is not working
  • Correctly identified (for all managed entities)
  • The problem of separate entities

According to business-ID (non-primary key field; How about foreign keys? Cover them

  • HashCode ()/the equals () is broken
  • Correct identity (for all managed entities)
  • Independent entities are fine

My question is: Did I miss anything?

Answer 1:

Read a very good article on the subject: Don’t let sleep mode steal your identity.

The conclusion of this paper is as follows:

When objects are persisted to a database, object identification is difficult to implement correctly. However, the problem is entirely in allowing objects to exist without an ID before being saved. We can solve these problems by assigning object ids from an object-relational mapping framework such as Hibernate. We can assign the object ID immediately after instantiating the object. This makes object identification simple and error-free and reduces the amount of code required in the domain model.