How do I query UUIDs stored as binary in a database (JPA/Hibernate/MySQL)

时光怂恿深爱的人放手 提交于 2021-02-07 02:36:52

问题


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 blog posting JPA and UUID Primary Keys which gets me some of the way there. Notice how the storage of the UUID is optimized by storing it in binary form (versus the string representation.

It solves part of the problem, because now we can insert objects efficiently into the database.

However, now I have an issue when I want to query from the database using EntityManager.createQuery. Is it possible/desirable to query against binary data? or, should I store the String UUID along-side the binary version to facilitate querying?


回答1:


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();



回答2:


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[]




回答3:


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.



来源:https://stackoverflow.com/questions/6629127/how-do-i-query-uuids-stored-as-binary-in-a-database-jpa-hibernate-mysql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!