I have a Java/JPA/Hibernate/MySQL based app. I want to use UUIDs for object identity, however I want to ensure database performance does not suffer.
I found this great b
As long as you already have the ID in binary format, querying it is simple:
byte[] id = ....;
em.createQuery(“SELECT x FROM TableName x WHERE x.id = ?1″, TableName.class).setParameter(1, id).getSingleResult();
Actually if you are just looking up by primary key you can use
em.find(TableName.class, id);
Getting the ID in binary format can be a bit of a pain, especially if you need to be passing it around in URLs etc. I recommend Base64 encoding / decoding it; Apache Commons Codec has helper methods from going from byte[] to URL-safe string and then back to byte[]
Tested with Hibernate 4.1.2 and MySQL-Connector-J 5.1.18, you can define a UUID field:
@Entity
class EntityType {
@Column( columnDefinition = "BINARY(16)", length = 16 )
private UUID id;
}
...and query with a UUID instance:
UUID id = ....;
EntityType result = em.createQuery(
“SELECT x FROM EntityType x WHERE x.id = ?1″, EntityType.class )
.setParameter( 1, id ).getSingleResult();
16 bytes overhead on 1 billion of records is roughly 15Gb. If you do have that much of the data you will have more serious scalability problems to solve and those 15Gb at 10 cents/Gb or less will not really be a big deal. Many to many relationships can grow to that size quicker but it will still be not that much to worry about.
To summarize, just go with string representation. It will save you a lot of effort in dealing with database at fairly small price.
P.S. My personal preference is to use numeric ids, but that's separate discussion.