java的UUID類型字段片部,如何通過jdbc進(jìn)行數(shù)據(jù)庫的CRUD
關(guān)鍵字:UUID byte[] jdbc mysql java
1镣衡、UUID/GUID概念
UUID含義是通用唯一識(shí)別碼 (Universally Unique Identifier)霜定,這 是一個(gè)軟件建構(gòu)的標(biāo)準(zhǔn),也是被開源軟件基金會(huì) (Open Software Foundation, OSF) 的組織應(yīng)用在分布式計(jì)算環(huán)境 (Distributed Computing Environment, DCE) 領(lǐng)域的一部份廊鸥。
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.
詳細(xì)介紹請(qǐng)參考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類中還有個(gè)方法也常用:UUID.fromString(name)
Creates a UUID from the string standard representation as described in the toString method.
3、數(shù)據(jù)庫中UUID的存儲(chǔ)類型
常用的存儲(chǔ)方式兩種吆视,以mySql數(shù)據(jù)庫為例(關(guān)于oracle數(shù)據(jù)庫典挑,測(cè)試后再貼)
字符串方式:char(36)
字節(jié)方式(二進(jìn)制):binaray(36)
創(chuàng)建表結(jié)構(gòu):
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列啦吧,參數(shù)為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[]轉(zhuǎn)換為UUID字符串
Assert.assertEquals(new String((byte[])id),uuid.toString());
Assert.assertEquals(UUID.fromString(ids).toString(),uuid.toString());
}
//delete
ps=conn.getConect().prepareStatement(sqlDelete);
//id列您觉,參數(shù)為byte[]或者String都可以
ps.setObject(1, uuid.toString().getBytes());
ps.executeUpdate();
}catch(Exception ex){
ex.printStackTrace();
}finally{
conn.close();
}
}catch(Exception e){
e.printStackTrace();
}
}