use-case: when we need to compare two objects to check their equality for satisfying some business rules.
In hibernate, we need to take care of some more factors in addition to what we do in Core Java.
- Hibernate mostly work with persistent objects only.
- when we have a persistent object in hibernate, that object represents both :-
– An instance of a class in a particular Java virtual machine (JVM)
– A row (or rows) in a database table (or tables)
We know enough around first concept. I will focus on second point.
Objects fetched from same session
Requesting a persistent object again from the same Hibernate session returns the same Java instance of a class, which means that you can compare the objects using the standard Java ‘==’ equality syntax.
Let’s see a quick example:
You see above that we got two instances on EmployeeEntity and both are actually same java object instance.
Objects fetched from different sessions
If you request a persistent object from more than one Hibernate session, Hibernate will provide distinct instances from each session, and the == operator will return false if you compare these object instances.
Let’s compare instances “
emp” and “
employeeObj1” in above example and you will get the result as false; because both are fetched in separate sessions.
So if you are comparing objects in two different sessions, you will need to implement the
equals() method on your Java persistence objects, which you should do as a regular occurrence anyway. (Just don’t forget to override
hashCode() along with it.)
Hibernate wraps the actual object in a proxy so always use the getter methods inside instead of actual properties to compare.
Now let’s add
equals() method as suggested and then see the behavior change while checking the equality of both instances on
Now let’s again check the equality using
equals() method. [‘==’ will return false, we know that].
Now both objects are equal logically as well as programmatically.
- Requesting a persistent object again from the same Hibernate session returns the “same java instance” of a class.
- Requesting a persistent object from the different Hibernate session returns “different java instance” of a class.
- As a best practice, always implement equals() and hashCode() methods in your hibernate entities; and always compare them using