prockel
prockel

Reputation: 263

equals() and hashcode() for JPA entities using EclipseLink

Using JPA, I stumbled upon the problem with equals() and hashcode(), especially for newly created entities which have not yet been persisted.

I found the following answer in stackoverflow:

Should I write equals() methods in JPA entities?

This answer talks about Hibernate sessions. I do not use Hibernate (but EclipseLink), and I don't know about implementation specifics of JPA providers, such as these "sessions".

My question is, what is a Hibernate session in terms of JPA? Or, more specific: If I don't override equals() and hashcode(), in which cases would I run into the problem where two objects representing the same entity (same business key, if one exists) are not "equal" (this means equals() returns false)?

Will using the same EntityManager instance be sufficient to not getting these problems (this means, can "session" and "EntityManager" be used equivalent in this context?)

Note: I don't have a usable business key for all tables, so the solution to use business key attributes in equals() and hashcode() cannot be applied.

Upvotes: 4

Views: 2320

Answers (2)

James
James

Reputation: 18379

EclipseLink does not have any specific requirements for equals() and hashCode() (even on Id classes).

Within a persistence context identity is maintained, so the default equals and hashCode would function.

For detached objects they will have different identity, so equals will not return true unless you override it to use the Id or some other criteria. This will not cause an issue with EclipseLink, but your application may have dependencies on this.

In general equals and hashCode should be implemented correctly if your objects are used in Sets or Maps, but EclipseLink always uses Identity Maps and Sets internally, so should have no issues internally.

Upvotes: 6

JB Nizet
JB Nizet

Reputation: 691943

You could have two detached instances of the same entity, or an attached one and a detached one, and they would thus not be equal, since the default equals method compares physical addresses.

It's almost impossible to implement good equals methods for entities without a business key. And even for entities with a business key, if this business key is mutable, we're doomed.

Upvotes: 1

Related Questions