如何取回以二进制形式存储在数据库中的Java UUID [英] how to get back the java UUID stored in DB as binary

查看:76
本文介绍了如何取回以二进制形式存储在数据库中的Java UUID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在转换后,我们有一个Java UUID字段以二进制字节的形式存储在数据库(MySQL)中

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;

然后使用resultSet.getBytes从数据库中检索它之后,字节数组将以以下方式转换回UUID

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);
}

这很好,直到现在我必须在生产中找到一行的UUID字段.显示记录的应用程序可能使用getText或getString来显示字节数组,仅通过获取结果字符串的字节数组(使用UTF-8)并应用我的toUUID方法,就无法获取记录的UUID值:(

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 :(

不幸的是,我们服务的所有检索端点都需要此UUID字段.我能否暗示一下如何使用该字节数组的字符串格式,然后将其转换回原始的UUID?

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?

推荐答案

我认为您可以通过UUID#fromString()方法将UUID字符串转换为真正的UUID对象.然后,您可以比较两个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;
}

如果不是具有引用的UUID,而是具有字节数组,则可以使用已经将字符串转换为UUID的toUUID()方法.

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.

请点击下面的演示链接,演示该字符串到UUID的转换是有效的,并且在逻辑上是正确的:

Follow the link below for a demo showing that the string to UUID conversion works and is logically correct:

演示

这篇关于如何取回以二进制形式存储在数据库中的Java UUID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆