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
2010-01-29 16:46:23
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
caskey
2010-01-29 16:48:01
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
2010-01-29 16:51:29
Try UUID.randomUUID(). You can then turn it into text via toString, and back again via UUID.fromString(uuidText)
Chamelaeon
2010-01-29 16:57:07
thanks for your help
ken
2010-01-29 17:12:03
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
2010-01-29 17:11:52