tags:

views:

327

answers:

2

In java persistence with hibernate, gavin suggests that we use business key for equality comparison. Business keys can not only involve multiple field comparisons, but there is no guarantee that the "perfect" business key's semantics will not change in future. We live in non ideal world and business requirements and laws change very frequently. In such case we will be left with data in db stored with multiple business key semantics. I want to break problem into 2 parts 1. When we strictly deal with persistent or detached objects. 2. When we deal with transient objects.

  1. I still don't see any downside on using a surrogate key for equality and hashcode if we are dealing with persistent and detached objects. 2 persistent objects or detached are equals if they same primary key . Is this wrong to assume ?

  2. When we deal with transient objects, we can use the business key semantics to compare objects and have a merge strategy available if you try to persist 2 transient objects with same business key but different values in remainder attribute

In read heavy applications, where most of the transactions are read/update, this strategy should yeild a better performance. As, i am new to hibernate, any suggestions are appreciated.

+1  A: 

The problem with object identity and Hibernate is to do with transient objects: when is the primary key created? If the answer's when you write to the DB (using DB-controlled primary key generation such as an Oracle sequence), then you have a potential problem.

If the primary key is used as the basis for equality checking and it's part of of the hash code generation then you will break the hashcode contract as the object won't be the same before and after the primary key is generated.

If you can, just use a generated primary key that you can set at object creation time (such as a UUID). This ensures your hash code and equality check remain consistent.

hbunny
+1 I Agree. I see no real benefit from using business keys, also means that you have to figure out a business key for every object and sometimes there isn't one. To my mind, using business keys gives you no real advantage if you set the id and use that (UUID) at object creation time.
Michael Wiles
+1  A: 

I used to agonize over finding the perfect business key for every class and would end up using a UUID in situations where there just wasn't anything unique that could never change. But now, I use the database surrogate key and avoid situations where I have to depend on equality for transient objects. It seems simpler, less prone to mistakes, and faster. It may depend on the type of application, but for typical CRUD apps, the object usually goes into the database before you have to deal with it in a collection.

Brian Deterling