Messing around with equals()

After some time leaving this topic alone. I came back to mess around with equals() again. This time I had in mind testing how equals behaves in the context of JPA especially with Hibernate as implementation and lazy loading. I bring this topic up again because Hibernate uses CGLIB to do bytecode enhancements by extending the entity class with an enhanced class. This doesn’t come for free, so there are certain restrictions one has to think about. Based on Core Java 2, Volume I – Fundamentals the equals() method must fulfill the requirements to be reflexive, symmetric, transitive and consistent. I ommit the obligatory handling of null. The book suggests a common way to implement the method.

@Override
public boolean equals(Object obj) {
  // a quick test to see if both objects are identical
  if (obj == this) { return true; }
  // must return false if explicit parameter is null
  if (obj == null) { return false; }
  // if classes (type) doesn't match they can't be equal
  // if the semantics of equality can be different in subclasses
  if (obj.getClass() != getClass()) { return false; }
  // or if the semantics of equality are the same for subclasses
  if (!(obj instanceof DomainObject)) { return false; }
  // now we know obj is a non-null DomainObject
  DomainObject other = (DomainObject) obj;
  // test whether fields have identical values
  return new EqualsBuilder(). ... .isEquals();
}

So what is the problem? The same entity as lazy loaded object and as normal loaded object aren’t equal. The reason is the type comparison with getClass(). So I have to use instanceof instead which is ok if the semantic of equality doesn’t change. But what if I have the same inheritance tree as in the book where Manager extends Employee but has a different semantic for equality. In this case no one can be sure that an Employee equals a Manager.

Schlagwörter: ,

Schreibe einen Kommentar

Trage deine Daten unten ein oder klicke ein Icon um dich einzuloggen:

WordPress.com-Logo

Du kommentierst mit Deinem WordPress.com-Konto. Abmelden / Ändern )

Twitter-Bild

Du kommentierst mit Deinem Twitter-Konto. Abmelden / Ändern )

Facebook-Foto

Du kommentierst mit Deinem Facebook-Konto. Abmelden / Ändern )

Google+ Foto

Du kommentierst mit Deinem Google+-Konto. Abmelden / Ändern )

Verbinde mit %s

%d Bloggern gefällt das: