Friday, June 18, 2010

Hibernate Entity equals - id or others

The Hibernate entity object represents a database table and the Java equals(Object o) method determines identity among entities for a given table.

Hibernate itself identifies rows from a table by their primary keys, following the principles of relational theory as developed by Edgar Codd in the 1960s. Today the id is typically generated automatically by Hibernate and the database engine.


A new theory says that an entity's equals method should not compare ids but should compare all attributes other than the id, i.e. value1 and value2 in the example above.

Arguments FOR comparing attributes other than the id
  • When creating new entities, the entity has no id assigned before it is saved to database, so the id cannot be used to determine identity.
  • It is the various attribute values, not the id, that make up the significance of any row of data.
Q. Would it not be inefficient to compare all the attributes rather than the id?
A. Differences would typically be encountered fairly rapidly making the additional processing negligible.

Arguments AGAINST comparing attributes other than the id
  • Hibernate lazy initialization can be triggered by a comparison after the Hibernate session has ended. Scenarios include cached entities.
  • Regardless of identical attribute values, if the ids are different then there are separate rows in the database.
  • The comparing of ids parallels relational theory, a central principle for all relational databases, also paralleled by Hibernate.

Bottom line

The Hibernate entity equals method should compare IDs.

No comments:

Post a Comment