Friday, January 04, 2008

Persistence Objects and Object Equality in Java

When implementing equals and hashCode methods in Persistence Domain Objects, it is natural instinct to assume that you will need to only compare its database key which is also known as surrogate key.

When you recommend this approach, bright mind people will dismiss this idea by making following arguments
  1. Java Language Specification says that two objects are equal only and only if their state is equal.
  2. In long lived enterprise applications (i.e. applications which will live longer than 5-6 years) the database key for some of the tables might have to be recycled because of the constraints of size of primary key field. In such case you can not use database key as two different records can have same primary key ( i.e. one before recycle and second after recycle)

In my opinion above arguments are only partially valid.
  1. In most application (including enteprise, scientific and novice), the equality operation requirement says that two objects are equal only if they represent the same physical entity regardless of their state. If two different objects share the state, they are identical but not equal. For example, in real life if you take snapshot of one person at the different times, the state of that person might be different, but these snapshot represent the same person. A record in database represents an entity. Similary two persons might share the state (such as name, physical attributes, health condition, place, academics, jobs etc.) but they ARE different persons and that is why govenment came up with an artifical concept such Social Security number to distinguish them.
  2. If two objects have same primary key because of recyle, these objects will have been created at least 5-6 years apart. Also since database is very strict about not allowing duplicate primary key, previous set of records must have been archived into dataware house and removed from the database used for OLTP. In such case I don't see why and how will you create these two objects in the same application. As a result, I don't see why will you into hypothetical problem described in the point 2.