I'm implementing equals()
, hashCode()
and toString()
of my entities using all the available fields in the bean.
I'm getting some Lazy init Exception on the frontend when I try to compare the equality or when I print the obj state. That's because some list in the entity can be lazy initialized.
I'm wondering what's the correct way to for implementing equals()
and toString()
on an entity object.
Java hashCode() An object hash code value can change in multiple executions of the same application. If two objects are equal according to equals() method, then their hash code must be same. If two objects are unequal according to equals() method, their hash code are not required to be different.
The hashcode() method returns the same hash value when called on two objects, which are equal according to the equals() method. And if the objects are unequal, it usually returns different hash values.
If two objects are equal(according to equals() method) then the hashCode() method should return the same integer value for both the objects. But, it is not necessary that the hashCode() method will return the distinct result for the objects that are not equal (according to equals() method).
equals()
and hashCode()
should be implemented using a business key - i.e. a set of properties that uniquely identify the object, but are not its auto-generated ID.
in toString()
you can put whatever information is interesting - for example all fields.
Use your IDE (Eclipse, NetBeans, IntelliJ) to generate all these for you.
In order to avoid LazyInitializationException
, no matter whether in equals()
or in your view (jsp), you can use OpenSessionInView
.
When you implement the equals and hashCode methods for Hibernate objects, it is important to
instanceof
insteadMore information:
Stackoverflow: overriding-equals-and-hashcode-in-java
Hibernate documentation: Equals and HashCode
Edit: the same rules about not accessing the class properties directly applies to toString method as well - only using the getters guarantees that the information really contained in the class is returned.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With