title: How to save a UUID as binary(16) in java
body: <p>I have a table TestTable with columns ID as binary(16) and name as varchar(50)</p>
  
  <p>I've been trying to store an ordered UUID as PK like in this article <a href="https://www.percona.com/blog/2014/12/19/store-uuid-optimized-way/" rel="noreferrer">Store UUID in an optimized way</a></p>
  
  <p>I see the UUID is saved in database as HEX (blob)</p>
  
  <p>So I want to save this ID from java but I am getting this error</p>
  
  <blockquote>
    <p>Data truncation: Data too long for column 'ID' at row 1</p>
  </blockquote>
  
  <p>I am currently using the library sql2o to interact with mysql</p>
  
  <p>So basically this is my code</p>
  
  <pre><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();
  </code></pre>
  
  <p>The partial id should be something like this <strong>11d8eebc58e0a7d796690800200c9a66</strong></p>
  
  <p>I tried this statement in mysql without issue</p>
  
  <pre><code>insert into testtable(id, name) values(UNHEX(CONCAT(SUBSTR(uuid(), 15, 4),SUBSTR(uuid(), 10, 4),SUBSTR(uuid(), 1, 8),SUBSTR(uuid(), 20, 4),SUBSTR(uuid(), 25))), 'Test2');
  </code></pre>
  
  <p>But I got the same error when I remove the unhex function. So how can I send the correct ID from Java to mysql?</p>
  
  <p><strong>UPDATE</strong></p>
  
  <p>I solved my problem inspired on the answer of <a href="https://stackoverflow.com/a/40297651/2532403">David Ehrmann</a>. But in my case I used the HexUtils from tomcat to transform my sorted UUID string into bytes[]:</p>
  
  <pre><code>byte[] final_id = HexUtils.fromHexString(partial_id);
  </code></pre>