We have a Java UUID field that is stored in database (MySQL) as binary bytes after the following conversion
private byte[] getUUIDtoBytes(UUID devId) {
byte[] uuidBytes = new byte[16];
ByteBuffer.wrap(uuidBytes)
.order(ByteOrder.BIG_ENDIAN)
.putLong(devId.getMostSignificantBits())
.putLong(devId.getLeastSignificantBits());
return uuidBytes;
And after retrieving it from DB using resultSet.getBytes, the byte array is converted back to UUID in the following way
private UUID toUUID(byte[] bytes) {
ByteBuffer byteBuffer = ByteBuffer.wrap(bytes);
Long high = byteBuffer.getLong();
Long low = byteBuffer.getLong();
return new UUID(high, low);
}
This works fine until now I have to find the UUID field of a row in production. The application that displays the record probably uses the getText or getString to show the byte arrays and just by getting the byte array of the result string (with UTF-8) and applying my toUUID method, I cannot get back the UUID value of the record :(
Unfortunately, all the retrieval endpoints of our service require this UUID field. Can I have some hint on how I may possibly use the string format of that byte array, and convert it back to the original UUID?
解决方案
I think you can convert your UUID string into a bona fide UUID object via the UUID#fromString() method. Then, you can compare the least and most significant bits fields of the two UUID which you have:
boolean UUIDIsEqual(UUID one, String twoInput) {
UUID two = UUID.fromString(twoInput);
if (one.getLeastSignificantBits() == two.getLeastSignificantBits() &&
one.getMostSignificantBits() == two.getMostSignificantBits()) {
return true;
}
return false;
}
If, instead of having a UUID for the reference you have a byte array, then you can just use the toUUID() method which you already have to convert the string to a UUID.
Follow the link below for a demo showing that the string to UUID conversion works and is logically correct: