Wednesday, August 27, 2008

Update to using UUIDs as primary keys

Some time ago, I blogged about using UUIDs as primary keys. To quickly recap, because programs can generate UUIDs directly, without having to consult an external ID-generation service such as a database, using UUIDs as primary keys enables developers to avoid having to deal with the differences between persistent and transient instances of the same class and allows them to develop classes that are completely independent of the database. And because UUIDs are globally unique, they facilitate the creation of system that can operate in a disconnected fashion and then sync up later.

After working with a system that uses UUIDs for primary keys, I come around to the idea that database-generated keys aren't so bad after all. But, I think that the key (pardon the pun) is to keep them in the database. To that end, I have been creating Java classes that have UUIDs and use them to implement equals and hashCode, but that simultaneously have an integer ID field that is assigned from the database. This strategy gives me the best of both worlds: The UUID enables me to maintain a database-independent identity for each object, but I can still use the smaller, faster integer ID for foreign keys within the database. My Java code doesn't use the integer ID at all, apart from mapping it to the database through Hibernate.

0 Comments:

Post a Comment

<< Home