关键字:UUID byte[] jdbc mysql java
1、UUID/GUID概念
UUID含义是通用唯一识别码 (Universally Unique Identifier),这 是一个软件建构的标准,也是被开源软件基金会 (Open Software Foundation, OSF) 的组织应用在分布式计算环境 (Distributed Computing Environment, DCE) 领域的一部份。
A UUID is a 16-byte (128-bit) number. In its canonical form, a UUID is represented by 32 hexadecimal digits, displayed in five groups separated by hyphens, in the form 8-4-4-4-12 for a total of 36 characters (32 digits and four hyphens). For example:
550e8400-e29b-41d4-a716-446655440000
There are 340,282,366,920,938,463,463,374,607,431,768,211,456 possible UUIDs (16 to the 32nd power), or about 3 × 1038.
详细介绍请参考http://en.wikipedia.org/wiki/Universally_Unique_Identifier。
2、java中的类java.Util.UUID
jdk1.5增加了类java.Util.UUID,用于方便生成UUID。
UUID uuid=UUID.randomUUID();
String uuidStr=uuid.toString();//生成的如:9b17a4f1-cae4-42ce-9cba-b899dcac8517
UUID类中还有个方法也常用:UUID.fromString(name)
Creates a UUID from the string standard representation as described in the toString method.
3、数据库中UUID的存储类型
常用的存储方式两种,以mySql数据库为例(关于oracle数据库,测试后再贴)
字符串方式:char(36)
字节方式(二进制):binaray(36)
创建表结构:
create table guid(id binary(36),uuid char(36));
4、jdbc如何操作
@Test
public void guid(){
UUID uuid=UUID.randomUUID();
String sqlSelect="select id,uuid from guid";
String sqlInsert="insert into guid(id,uuid) values(?,?)";
String sqlDelete="delete from guid where id=?";
try{
JDBConnection conn=new JDBConnection();
try{
//insert
PreparedStatement ps=conn.getConect().prepareStatement(sqlInsert);
//id列,参数为byte[]或者String都可以
ps.setObject(1, uuid.toString().getBytes());
//uuid列
ps.setString(2, uuid.toString());
ps.executeUpdate();
//select
ResultSet result=conn.executeQuery(sqlSelect);
while(result.next()){
Object id=result.getObject(1);//获取的byte[]
Object uid=result.getObject(2);
String ids=result.getString(1);
Assert.assertEquals(uid, uuid.toString());
Assert.assertEquals(ids,uuid.toString());
//byte[]转换为UUID字符串
Assert.assertEquals(new String((byte[])id),uuid.toString());
Assert.assertEquals(UUID.fromString(ids).toString(),uuid.toString());
}
//delete
ps=conn.getConect().prepareStatement(sqlDelete);
//id列,参数为byte[]或者String都可以
ps.setObject(1, uuid.toString().getBytes());
ps.executeUpdate();
}catch(Exception ex){
ex.printStackTrace();
}finally{
conn.close();
}
}catch(Exception e){
e.printStackTrace();
}
}