Search code examples
javaspringuuidjdbctemplate

How to return generated UUID primary key


I am working with mySQL database and the table has a primary key in UUID format, generated by the database engine. I am using Spring framework JdbcTemplate (https://docs.spring.io/spring/docs/current/javadoc-api/index.html?org/springframework/jdbc/core/JdbcTemplate.html) to perform all operation. But on inserts I do need to return primary key to the caller. JdbcTemplate has method public int update(PreparedStatementCreator psc, KeyHolder generatedKeyHolder) but it returns integer keys only. KeyHolder interface also allow only numeric keys. Does someone know how to overcome this deficiency? Should I use something other than JdbcTemplate? It is not desirable, but possible. Give me a hint, please.


Solution

  • One way to do that is to create UUID in your java in advance and then pass it on to (SQL/DB), so in this case, you already know whats going to be your Primary key. since in theory UUID is unique there should be no collision.

    UUID uuid = UUID.randomUUID();
    jdbcTemplate.update("INSERT INTO users ( user_uuid , first_name , last_name) VALUES (?,?,?)",
                    "admin", uuid, user.getFirstName(), user.getLastName());
    //uuid: you already have the PrimeryKey in advance