views:

36

answers:

3

I am using Java EE and the Spring framework. I am writing my POJOs, and the base object for my system should have a globally unique ID. My question is: what would be a "best-practice" way for me to generate this ID. This id must also be stored in a db table as a primary key.

+2  A: 

The UUID class does a pretty good job of generating universally unique identifiers: here it is in the Java API.

Chamelaeon
A: 

UUIDs are what you are looking for. There are java util classes for working with them.

http://java.sun.com/javase/6/docs/api/java/util/UUID.html

http://www.ietf.org/rfc/rfc4122.txt

http://www.itu.int/ITU-T/asn1/uuid.html

caskey
Thanks. I looked through the links but am still confused as to how to generate a UUID. Could you please show me (or link to the site) how to actually generate a new UUID? Thanks
ken
Try UUID.randomUUID(). You can then turn it into text via toString, and back again via UUID.fromString(uuidText)
Chamelaeon
thanks for your help
ken
A: 

If you're using it as a primary key in the database, it may be better to use a sequence from within the database. Depends heavily on what you're doing, but in general I find it's better to do it this way since you can then leverage database constraints and such. (IE - let the db take care of making sure the PK is unique, not null, etc.)

Quotidian