UUID's with Hibernate/JPA
I have long been accustoming to storing UUID values in binary database columns (e.g. BYTEA
for PostgreSQL, BINARY(16)
for MySQL). When using Hibernate and JPA, I can annotate my entity fields like this...
@Id
@Column(name = "id", columnDefinition = "BINARY(16)")
private UUID id;
... and it just works.
UUID's with JDBC
On the occasions in which I've needed to write use JDBC, I've written UUID values like this...
PreparedStatement ps = new PreparedStatement("INSERT INTO foo (id) VALUES (?)");
ps.setObject(1, uuid, Types.BINARY)
... and read UUID values like this...
while (rs.net() {
UUID id = UUID.nameUUIDFromBytes(rs.getBytes("id"));
}
Mix and match?
Recently I took a MySQL database used by a Hibernate/JPA application, exported and imported it with the mysqldump
tool, and tried using the data with some raw JDBC code. The Hibernate/JPA code and read and write UUID's, and the raw JDBC code can read and write UUID's. However, if I:
- Use JDBC to read in a UUID that was originally written by Hibernate/JPA, and
- Have my JDBC code write that same UUID elsewhere, then
- The value stored in MySQL by the JDBC code does not match the original value!
Has anyone ever seen this before, or have any theories? I don't fully understand how Hibernate/JPA is serializing the UUID value under the covers, so I'm not sure what I might need to do differently with my raw JDBC code to produce the same result.
Thanks!