了解UUID

UUID是指在一台机器上生成的数字,它保证对在同一时空中的所有机器都是唯一的。通常平台会提供生成UUID的API。UUID按照开放软件基金会 (OSF)制定的标准计算,用到了以太网卡地址、纳秒级时间、芯片ID码和许多可能的数字。由以下几部分的组合:当前日期和时间(UUID的第一个部分与时间有关,如果你在生成一个UUID之后,过几秒又生成一个UUID,则第一个部分不同,其余相同),时钟序列,全局唯一的IEEE机器识别号(如果有网卡,从网卡获得,没有网卡以其他方式获得),UUID的唯一缺陷在于生成的结果串会比较长。关于UUID这个标准使用最普遍的是微软的GUID (Globals Unique Identifiers)。

UUID 在所有计算机上都是唯一的。不过,它们的值是完全随机的,因此不能用来确定添加值的时间或值的顺序。另外,UUID 值比其它方法(包括全局自动增量)所需的值大得多,并且在主键表和外键表中都需要更多的表空间。使用 UUID 建立表索引的效率也更低。

标准的UUID格式为:xxxxxxxx-xxxx-xxxx-xxxxxx-xxxxxxxxxx (8-4-4-4-12)

JDK中的UUID实现

从JDK 5.0开始自带了UUID的实现 java.util.UUID,示例用法如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import java.util.UUID;
public class TestUUID {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
for (int i = 0; i < 10; i ++) {
System.out.println(UUID.randomUUID().toString());
}
}
}

输出如下结果:

1
2
3
4
5
6
7
8
9
10
2bc58ecd-dd48-4144-b5aa-2ebebaad300c
468a36ed-2eec-42fc-9524-d04a404a5d94
e43ea34d-3768-4ad0-8f28-dd8e61267103
dba317d5-688e-4656-bea5-4542b414481d
f40408bb-df92-4118-8265-1e83f2810ae2
386e7c9d-b2af-4787-a171-6b1d9f350193
77a2eb19-0541-4fc3-a014-1b70840c42ec
4a00304e-d7e7-4a6f-bef3-4fb40ed7e1c2
631fdb01-1505-44e9-9e1b-3d84083651da
bdb68883-ff9b-4b56-a825-940f45b3b3db

Hibernate中的使用

UUID algorithm
The UUID contains: IP address, startup time of the JVM (accurate to a quarter second), system time and a
counter value (unique within the JVM). It’s not possible to obtain a MAC address or memory address from Java
code, so this is the best we can do without using JNI.

从hibernate reference中抄了个例子如下:

1
2
3
4
5
6
7
8
9
10
11
<class name="eg.Person" table="person">
<id name="Key" column="pid" type="string">
<generator class="uuid" />
</id>
<property name="birthday" type="date" />
<component name="Name" class="eg.Name"><!-- class attribute optional -->
<property name="initial" />
<property name="first" />
<property name="last" />
</component>
</class>

显示 Gitment 评论