java 二进制 数据库,如何取回以二进制形式存储在数据库中的Java UUID

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:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值