Menu

#5 JPA/Hibernate reference objects don't equate

v1.0_(example)
open
nobody
1
2014-09-05
2014-09-05
Anonymous
No

If I have an entity that is lazily loaded and it gets compared to another entity with the same id that was not lazily loaded then they show up as unequal.

An example can be found on this question: http://stackoverflow.com/questions/14024444/hibernate-javassist-proxies-and-objectequals

For my example: take any typical Employee entity that has an id. Running the following in a unit test will fail: (omitting entity manager creation)

@Test
public void testEmployeeEquals(){
    Long id = this.findFirstIdFromQuery("select top 1 employeeId from Employee where supervisorId is not null");
    Employee employeeRef = em.getReference(Employee.class, id);
    Employee employee = em.find(Employee.class, id);
    Assert.assertTrue(employee.equals(employeeRef));
}

My solution, as per the answer on stackoverflow, is to implement my own equals method using the "isAssignableFrom" method.

@Override
public boolean equals(Object obj) {
    if (this == obj)
        return true;
    if (obj == null)
        return false;
    if (!getClass().isAssignableFrom(obj.getClass()))
        return false;
    Employee other = (Employee) obj;
    if (getEmployeeId() == null) {
        if (other.getEmployeeId() != null)
            return false;
    } else if (!getEmployeeId().equals(other.getEmployeeId()))
        return false;
    return true;
}

@Override
public int hashCode() {
    return employeeId.hashCode();
}

It is my opinion that pojomatic should account for this. However, some could make the argument that the objects are not equal and that this is not a bug.

Discussion

Anonymous
Anonymous

Add attachments
Cancel





Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.