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

spike07 picture spike07 · Mar 15, 2010 · Viewed 31.4k times · Source

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.

Answer

Bozho picture Bozho · Mar 15, 2010

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.