使用Java读取MySQL二进制(16)UUID [英] Read MySQL binary(16) UUID with Java

查看:293
本文介绍了使用Java读取MySQL二进制(16)UUID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这应该是一个非常简单的问题,我只是在这里遗漏了一些基本知识,而我正在那些日子中的一个... 不能使用Hibernate或其他ORM.使用Java PreparedStatement.

This should be a very simple question, I'm just missing something basic here and I'm having 'one of those days...' Cannot use Hibernate or other ORM. Using Java PreparedStatement.

MySQL内容:

CREATE TABLE `article` (
  `articleID` binary(16) NOT NULL,
  `publisherID` bigint(20) DEFAULT NULL,
  PRIMARY KEY (`articleID`),
) ENGINE=InnoDB DEFAULT CHARSET=utf8$$

insert into article ( articleID, publisherID )
values ( (UNHEX(REPLACE(UUID(),'-',''))), 1111  );

Java内容

PreparedStatement ps = connection.prepareStatement( "select articleID, publisherID from article" );
ResultSet rs = ps.executeQuery();
while( rs.next())
{
  byte[] artIDArr = rs.getBytes( "articleID" );
  UUID artID = UUID.nameUUIDFromBytes( artIDArr );
}

rs.close();
ps.close();

现在,从数据库中读取UUID ...

Now, reading the UUIDs from the database...

    select hex(articleID) from article;

1C711C50E4773873AB1533401E2F420C
A1FCD341EE9311E297B700FFB00BB509
A95E06B6EEE611E297B700FFB00BB509

但是丢弃我在Java代码中读取的内容:

But dumping out what I read in the java code:

6c825dc9-c98f-37ab-b01b-416294811a84
de6337f9-f276-3e30-b9a3-8d9338a1977f
57ccb5af-1a66-329f-b069-69638e1af24f

现在,这是因为在将破折号存储为二进制之前我要从UUID中删除破折号,而补水是假设它们在那儿吗?

Now, is this because I'm removing the dashes from the UUID before storing them as binary, and the rehydration is assuming they're there?

将MySql中以二进制(16)存储的UUID读取到Jav UUID对象的正确方法是什么?

What is the correct method for reading a UUID stored as binary(16) in MySql to a Jav UUID object?

如果我将prepareStatment查询更改为选择hex(articleID)作为articleID ..."并以字符串形式读取它,那当然是数据库所包含的内容,但是UUID会引发异常,因为缺少字符串破折号...

if I change the the preparedStatment query to "select hex(articleID) as articleID..." and read it as a string, it's of course what the DB contains, but UUID throws an exception because the string is missing the dashes...

推荐答案

UUID artID = UUID.nameUUIDFromBytes(artIDArr);

使用MD5并修补字节.使用类似的东西

Uses MD5 and patches bytes. Use something like

static UUID toUUID(byte[] bytes) {
    if (bytes.length != 16) {
        throw new IllegalArgumentException();
    }
    int i = 0;
    long msl = 0;
    for (; i < 8; i++) {
        msl = (msl << 8) | (bytes[i] & 0xFF);
    }
    long lsl = 0;
    for (; i < 16; i++) {
        lsl = (lsl << 8) | (bytes[i] & 0xFF);
    }
    return new UUID(msl, lsl);
}
UUID artID = toUUID(artIDArr);

这篇关于使用Java读取MySQL二进制(16)UUID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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