codereviewanskquestions
codereviewanskquestions

Reputation: 13988

UUID as entity id

I am using hibernate + mysql in my java application and I'd like to generate a unique string id (UUID) when I am inserting an entry into a table.

How do I create a table so that I can automatically generate uuid and use it as entity key?

+------------+-------------------------------------+
| uuid       | name                                |
+------------+-------------------------------------+
| asdf1221   | name 1                              |
| sksdkfk1   | name 2                              |
+------------+-------------------------------------+

Upvotes: 1

Views: 918

Answers (2)

Jacob
Jacob

Reputation: 1916

I will suggest you to generate the uuid in Java.

  1. Java UUID.randomUuid() is of type 4, which is cryptographically strong; while MySQL uuid() is of type 1 which is time based and relatively easy to be predicted.

If security is your concern, do it in Java.

  1. As mentioned by Stephen, binary(16) is more efficient when storing uuid in database.

Hibernate has the native support from concerting between database binary (16) and java UUID. Just set the field type to UUID in your Java entity with column definition as Binary (16).

Upvotes: 0

StephenS
StephenS

Reputation: 2136

MySQL doesn't allow a function for a default value, but see Can I use a function for a default value in MySql? for how to create a trigger to do this.

Note that MySQL's UUID() returns a CHAR(36), and storing UUIDs as text (as shown in those answers) is obviously inefficient. Instead, the column should be BINARY(16), and you can use UUID_TO_BIN() when inserting data and BIN_TO_UUID() when reading it back.

Upvotes: 1

Related Questions