Reputation: 13988
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
Reputation: 1916
I will suggest you to generate the uuid in Java.
If security is your concern, do it in Java.
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
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