Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entities equals(), hashCode() and toString(). How to correctly implement them?

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.

like image 968
spike07 Avatar asked Mar 15 '10 11:03

spike07


People also ask

How do we implement hashCode () and equals ()?

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.

What is the hashCode () and equal () function?

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.

What is the relationship between hashCode () and equals () method in Java?

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).


2 Answers

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.

like image 149
Bozho Avatar answered Oct 12 '22 00:10

Bozho


When you implement the equals and hashCode methods for Hibernate objects, it is important to

  1. Use getters instead of directly accessing the class properties.
  2. Not directly compare objects' classes, but use instanceof instead

More 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.

like image 37
simon Avatar answered Oct 11 '22 23:10

simon