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

后端 未结 3 961
再見小時候
再見小時候 2021-02-15 17:37

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

3条回答
  •  终归单人心
    2021-02-15 17:51

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

提交回复
热议问题