那么我们先看看什么是UUID?简单的说,UUID是指在一台机器上生成的数字,它保证对在同一时空中的所有机器都是唯一的。在UUID的算法中,可能会用到诸如网卡MAC地址,IP,主机名,进程ID等信息以保证其独立性.
优点:
能够保证独立性,程序可以在不同的数据库间迁移,效果不受影响。
保证生成的ID不仅是表独立的,而且是库独立的,这点在你想切分数据库的时候尤为重要。
缺点:
比较占地方,和INT类型相比,存储一个UUID要花费更多的空间。
使用UUID后,URL显得冗长,不够友好。
那么到底使用不使用UUID做主键呢?? http://hi.baidu.com/thinkinginlamp/blog/item/c609d10979710e81d0581b60.html
那么如何生成UUID,一个自动生成不重复文本的函数,Hibernate提供的uuid.
hibernate中的uuid是自动生成主键的一种机制,但是它依赖于hiberbate包,刚刚将它从Hibernate中提取出来,(从其他博客和公司的组件代码中发现了UUID的生成类)供各位使用.
优点:
能够保证独立性,程序可以在不同的数据库间迁移,效果不受影响。
保证生成的ID不仅是表独立的,而且是库独立的,这点在你想切分数据库的时候尤为重要。
缺点:
比较占地方,和INT类型相比,存储一个UUID要花费更多的空间。
使用UUID后,URL显得冗长,不够友好。
那么到底使用不使用UUID做主键呢?? http://hi.baidu.com/thinkinginlamp/blog/item/c609d10979710e81d0581b60.html
那么如何生成UUID,一个自动生成不重复文本的函数,Hibernate提供的uuid.
hibernate中的uuid是自动生成主键的一种机制,但是它依赖于hiberbate包,刚刚将它从Hibernate中提取出来,(从其他博客和公司的组件代码中发现了UUID的生成类)供各位使用.
import java.net.InetAddress;
/**
*
* @author zhangguang
*
*/
public class UUIDHexGenerator {
private static final int IP;
private static UUIDHexGenerator instance = null;
private static short counter = (short) 0;
private static final int JVM = (int) ( System.currentTimeMillis() >>> 8 );
private String sep = "";
static {
int ipadd;
try {
ipadd = toInt( InetAddress.getLocalHost().getAddress() );
}
catch (Exception e) {
ipadd = 0;
}
IP = ipadd;
}
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 static int toInt( byte[] bytes ) {
int result = 0;
for (int i=0; i<4; i++) {
result = ( result << 8 ) - Byte.MIN_VALUE + (int) bytes[i];
}
return result;
}
protected int getJVM() {
return JVM;
}
protected short getCount() {
synchronized(UUIDHexGenerator.class) {
if (counter<0) counter=0;
return counter++;
}
}
/**
* @author zhangguang
*
* @return UUID. 一組 UUID,係由一串 16 位元組(亦稱 16 字節,或 128 位元)的16進位數字所構成
*/
public String 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();
}
protected int getIP() {
return IP;
}
protected short getHiTime() {
return (short) ( System.currentTimeMillis() >>> 32 );
}
protected int getLoTime() {
return (int) System.currentTimeMillis();
}
public static UUIDHexGenerator getInstance()
{
if (instance == null)
instance = new UUIDHexGenerator();
return instance;
}
public static void main( String[] args ) throws Exception {
for ( int i=0; i<10; i++) {
String id = getInstance().generate();
System.out.println(id);
String id2 = getInstance().generate();
System.out.println(id2);
}
}
}