I'm really attracted to the idea of generating my primary keys outside of the database, before I insert the data into the database, using java.util.UUID for the primary key.
One thing I'm wondering about is what's the best way to store the UUID in the database. My current strategy is to convert it to a base 36 number as a string and use that;The abs() is just to get rid of the unaesthetic minus signs; I prefer just letters and digits.Code:public static String uuid36() { final UUID uuid = UUID.randomUUID(); final long hi = abs(uuid.getMostSignificantBits()); final long low = abs(uuid.getLeastSignificantBits()); return (Long.toString(hi, 36) + Long.toString(low, 36)); } private static long abs(long arg) { if (arg < 0L) return (-arg); return (arg); }
That produces a string that's at most 26 chars.
An alternative would be to store the 2 longs in binary format, as 16 bytes. Using the jdk my idea would be to convert each to an unsigned hex string, concatenate those and give it to the BigInteger constructor, then call its toByteArray() to get the 16 bytes. Sounds like that could be slow.
So my first question is, which would you do? (Assuming that this idea isn't too hair-brained.)
The other part of this is that it seems like I should be able to use this 128 bit UUID primary key as the object's hashCode and identity. But I was reading somewhere on the Hibernate site and they recommended against doing this, although they were generating their uuid in Hibernate. They said that it was bad to tie the database stuff, PK, to the business logic, hash code. But to me it seems like it works out.
I could also use the UUID as the object's business identity, and let the database generate the PKs. Then I have 2 ids in the database.
The object's business identity is also going to be used as the name of files; I'm trying to make a online photo album. (Something to keep up on Java while I do C# programming at work.)
There was also this thread which discussed similar issues.
http://forum.springframework.org/showthread.php?t=40953
Anyhow, I'm curious to know what others think.
Thanks


Reply With Quote
