Equals () and hashcode () for JPA objects using EclipseLink

Using JPA, I came across a problem with equals() and hashcode() , especially for newly created objects that have not yet been saved.

I found the following answer on stackoverflow:

Should I write equals () methods in JPA objects?

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

My question is: what is a Hibernate session from a JPA perspective? Or more specifically: if I do not redefine equals() and hashcode() , in which cases I would run into a problem when two objects representing the same object (the same business key, if one exists) are not " equal to "(does this mean that equals() returns false)?

Will the same EntityManager instance be used to not get these problems (does this mean that in this context you can use the equivalent in "session" and "EntityManager"?)

Note. I do not have a useful business key for all tables, so the decision to use the business key attributes in equals() and hashcode() cannot be applied.

+4
source share
2 answers

EclipseLink has no special requirements for equals () and hashCode () (even in Id classes).

The persistence context constant is saved inside, so the default values ​​and hashCode will be used.

They will have different identities for individual objects, so equals will not return true unless you redefine it to use Id or some other criteria. This will not cause a problem 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 maps and sets of identifiers inside, so there should be no problems inside.

+6
source

You can have two separate instances of the same object or attached and separate, and therefore they will not be equal, since the default method is equal to physical addresses.

It is almost impossible to implement good peer methods for objects without a business key. And even for objects with a business key, if this business key is volatile, we are doomed.

+1
source

All Articles