您的位置:首页 > 产品设计 > UI/UE

Hibernate的uuid主键生成方式

2011-03-16 15:35 507 查看
 

一、用一个128-bit的UUID算法生成字符串类型的标识符。

二、在一个网络中唯一(生成算法使用了IP地址)。

三、UUID被编码为一个32位16进制数字的字符串。
数据库相应的主键字段应该是varchar或者char型,32位,如果少于32位,在增加记录的时候你也许会遇到“ORA-01401: 插入的值对于列过大”的错误。

四、不推荐写成uuid.hex 推荐直接写成uuid 
从hibernate3.0开始已经不再支持uuid.string,查看changelog可以发现: Changes in version 3.0 beta 1 (21.12.2004) * removed uuid.string and renamed uuid.hex to plain uuid,hibernate3.x的api中AbstractUUIDGenerator类只有UUIDHexGenerator子类了,使用时在hibernate的映射文件中,配置成<generator class="uuid"/>;(其实写成uuid.hex也是可以用的,但官方的reference文档中是uuid,所以不推荐写成uuid.hex)

五、hibernate中uuid.hex的生成算法

package com.wallimn.util;

import java.io.Serializable;
import java.net.InetAddress;
/**
* 唯一主键生成办法。从Hibernate中提取出来。
*/
public class UUIDGenerator {

private static final int IP;
public static int IptoInt( byte[] bytes ) {
int result = 0;
for (int i=0; i<4; i++) {
result = ( result << 8 ) - Byte.MIN_VALUE + (int) bytes[i];
}
return result;
}
static {
int ipadd;
try {
ipadd = IptoInt( InetAddress.getLocalHost().getAddress() );
}
catch (Exception e) {
ipadd = 0;
}
IP = ipadd;
}
private static short counter = (short) 0;
private static final int JVM = (int) ( System.currentTimeMillis() >>> 8 );

public UUIDGenerator() {
}

/**
* Unique across JVMs on this machine (unless they load this class
* in the same quater second - very unlikely)
*/
protected int getJVM() {
return JVM;
}

/**
* Unique in a millisecond for this JVM instance (unless there
* are > Short.MAX_VALUE instances created in a millisecond)
*/
protected short getCount() {
synchronized(UUIDGenerator.class) {
if (counter<0) counter=0;
return counter++;
}
}

/**
* Unique in a local network
*/
protected int getIP() {
return IP;
}

/**
* Unique down to millisecond
*/
protected short getHiTime() {
return (short) ( System.currentTimeMillis() >>> 32 );
}
protected int getLoTime() {
return (int) System.currentTimeMillis();
}

private final static String sep = "";

protected String format(int intval) {
String formatted = Integer.toHexString(intval);
StringBuffer buf = new StringBuffer("00000000");
buf.replace( 8-formatted.length(), 8, formatted );
return buf.toString();
}

protected String format(short shortval) {
String formatted = Integer.toHexString(shortval);
StringBuffer buf = new StringBuffer("0000");
buf.replace( 4-formatted.length(), 4, formatted );
return buf.toString();
}

public Serializable generate() {
return new StringBuffer(36)
.append( format( getIP() ) ).append(sep)
.append( format( getJVM() ) ).append(sep)
.append( format( getHiTime() ) ).append(sep)
.append( format( getLoTime() ) ).append(sep)
.append( format( getCount() ) )
.toString();
}

}
 

算法为引用。原文地址:http://wallimn.javaeye.com/blog/327844
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息