Sunday, September 17, 2006

Identity with UUID

Don't Let Hibernate Steal Your Identity "This example uses the object id as the definition of equals() and to derive hashCode(). This is much simpler. However, to make this work we need two things. First, we need a way to ensure every object has an id even before it is saved. This example assigns the id a value as soon as the id variable is declared. Second, we need a way to determine if this is a newly created object, or a previously saved object. In our original example, Hibernate checked whether the id field was null to determine if the object was new. Obviously this won't work anymore since our object id is never null. We can easily solve this by configuring Hibernate to check whether the version field, rather than the id field, is null. The version field is a much more appropriate indicator of whether your object has been previously saved."

"Furthermore, the new definition of equals() and hashCode() is universal for all objects that contain an object id. That means we can move those methods to an abstract parent class. We no longer need to re-implement equals() and hashCode() for every domain object, and we no longer need to think through which combination of fields is both unique and immutable for each class. Instead, we simply extend the abstract parent class. Of course, we don't want to force our domain objects to extend from a parent class, so we'll also define an interface to keep things flexible."

"We now have a simple and effective way to create domain objects. They extend AbstractPersistentObject, which automatically gives them an id when they're first created and properly implements equals() and hashCode(). They also get a reasonable default implementation of toString() that they can optionally override. If this is a test object or an example object for a query-by-example the id can be changed or set to null. Otherwise it should not be altered. If for some reason we need to create a domain object that extends some other class, it can implement the PersistentObject interface rather than extend the abstract class."
Post a Comment