How to save UUID as binary in Java (16)
I have a table TestTable. The column ID is binary (16) and the name is varchar (50)
I have been trying to store ordered UUIDs as PK, as described in article store UUID in an optimized way
I see that UUID is saved in the database as hex (BLOB)
So I want to save this ID from Java, but I received this error
I am currently using the sql2o library to interact with MySQL
So basically this is my code
String suuid = UUID.randomUUID().toString(); String partial_id = suuid.substring(14,18) + suuid.substring(9,13) + suuid.substring(0,8) + suuid.substring(19,23) + suuid.substring(24) String final_id = String.format("%040x",new BigInteger(1,partial_id.getBytes())); con.createQuery("INSERT INTO TestTable(ID,Name) VALUES(:id,:name)") .addParameter("id",final_id) .addParameter("name","test1").executeUpdate();
The partial ID should be 11d8eebc58e0a7d796690800200c9a66
I tried this statement in mysql, no problem
insert into testtable(id,name) values(UNHEX(CONCAT(SUBSTR(uuid(),15,4),SUBSTR(uuid(),10,1,8),20,25))),'Test2');
But when I delete the unhex function, I get the same error So how can I send the correct ID from Java to MySQL?
UPDATE
I solved my problem in David Ehrmann's answer But in my case, I use hexutils in Tomcat to convert my sorted UUID string to bytes []:
byte[] final_id = HexUtils.fromHexString(partial_id);
Solution
Try to store it as bytes:
UUID uuid = UUID.randomUUID(); byte[] uuidBytes = new byte[16]; ByteBuffer.wrap(uuidBytes) .order(ByteOrder.BIG_ENDIAN) .putLong(uuid.getMostSignificantBits()) .putLong(uuid.getLeastSignificantBits()); con.createQuery("INSERT INTO TestTable(ID,:name)") .addParameter("id",uuidBytes) .addParameter("name","test1").executeUpdate();
A little explanation: your table is using binary (16), so serializing UUIDs into raw bytes is a very simple method UUID is essentially a 128 bit integer with some reserved bits, so the code writes it as a big endian 128 bit int. ByteBuffer is just a simple way to convert two long into a byte array
Now, virtually all the conversion work and headaches are not worth saving 20 bytes per line