Eclipse and Problem With Auto Generated Equals()

JSF table <rich:dataTable> was using HashMap to represent data. This Map contained objects collected from the database. After saving new objects to Db and table refresh it showed objects completely different from what we expected. After a few hours of searching for a bug in our code or in JSF code it appeared that the problem lay in another place.

Eclipse generates equals method checking if classes of compared objects are the same:

    if (getClass() != obj.getClass()) {
        return false;
    }

and such behavior combined with Hibernate can cause some problems because very often while loading data from Db instead of object of our class Hibernate creates proxy object extending base class we are loading. And then equals method comparing getClass() returns false causing strange HashMap behavior. Solution is very simple: instead of getClass() you should use instanceof.

Additionally, as I read in a comment on Proxorkut blog, if we use lazy loading in entity classes we should use getXXX() methods in equals() and hashCode() to get variable values because if we try to get them directly from the fields, Hibernate might not initialize them before we try to use them.

Written by

Tomasz Dziurko

VP of Engineering at [SoftwareMill](https://softwaremill.com), a 100% remote software consultancy and part of the VirtusLab group. I build engineering organizations that scale without losing the people who make them work. [More about me]({{site.baseurl}}/about-me/)