关于Java:通过注释使用Hibernate UUIDGenerator

Using Hibernate UUIDGenerator via annotations

我使用我的uuid如下:

1
2
3
4
5
@Id
@GeneratedValue(generator ="uuid")
@GenericGenerator(name ="uuid", strategy ="uuid")
@Column(name ="uuid", unique = true)
private String uuid;

但是我收到了一个聪明的Hibernate警告:

Using
org.hibernate.id.UUIDHexGenerator
which does not generate IETF RFC 4122
compliant UUID values; consider using
org.hibernate.id.UUIDGenerator instead

所以我想切换到org.hibernate.id.UUIDGenerator,现在我的问题是如何将其告知Hibernate的生成器。 我看到有人用它作为"休眠uuid"-这是我尝试过的方法,但结果是负面的:

1
2
3
4
5
@Id
@GeneratedValue(generator ="hibernate-uuid")
@GenericGenerator(name ="hibernate-uuid", strategy ="hibernate-uuid")
@Column(name ="uuid", unique = true)
private String uuid;

它应该是uuid2

1
2
3
...
@GenericGenerator(name ="uuid", strategy ="uuid2")
...

见5.1.2.2.1。各种其他发电机。


HibernateDoc说您可以使用以下内容:

1
2
3
4
5
@Id
@GeneratedValue(generator="system-uuid")
@GenericGenerator(name="system-uuid", strategy ="uuid")
@Column(name ="uuid", unique = true)
private String uuid;

我希望您正在使用Hibernate 3.5。


尝试...

1
2
3
4
5
6
7
8
9
10
11
12
13
@Id
@GeneratedValue(generator ="uuid2")
@GenericGenerator(name ="uuid2", strategy ="uuid2")
@Column(name ="uuid", columnDefinition ="BINARY(16)")
public UUID getId()
{
    return id;
}

public void setId(UUID i)
{
    id = i;
}

注意" uuid2"而不是" uuid"。


正如@natan在评论中指出的那样,如果您使用的是Hibernate 5,那么下面的代码就足够了:

1
2
3
@Id
@GeneratedValue
private java.util.UUID id;

在MySQL中用BINARY(16)类型定义id列,或者在其他SQL实现中等效。


这将使用UUID v4,并且自动生成的uuid将像通常varchar(36)一样存储在列中:

1
2
3
4
5
@Id
@GeneratedValue(generator ="uuid2")
@GenericGenerator(name ="uuid2", strategy ="uuid2")
@Column(length = 36)
private String uuid;

这应该会对性能产生一些影响:

  • 消耗的大小大于BINARY(16)
  • 水化后,java.lang.String实例比java.util.UUID消耗更多的内存:UUID作为字符串使用112字节,而对于UUID使用32字节(即两个longs + obj标头)。

但是,使用带字符串的UUID会更容易-编写查询更容易,并且您可以看到表的内容。

在Hibernate 5.3上测试


Unknown Id.generator: hibernate-uuid

1
2
3
4
5
6
7
8
9
10
11
@Id
@GeneratedValue(generator ="uuid")
@GenericGenerator(name ="uuid", strategy ="org.hibernate.id.UUIDGenerator")
@Column(name ="id", unique = true)
public String getId() {
    return id;
}

public void setId(String id) {
    this.id = id;
}


在当前的5.4.2 Hibernate版本中,

如果要在数据库表中使用人类可读的varchar(36)字段,
而且您的Java类中还有一个可序列化的UUID数据类型,
您可以在使用java.util.UUID类型声明字段成员的同时使用@Type(type ="uuid-char")

请注意,@Column(length = 36)对于将MySQL中的字段长度从255减少到36非常重要。

请注意,对于PostgreSQL,您应该改用@Type(type ="pg-uuid")

1
2
3
4
5
6
7
8
9
import org.hibernate.annotations.Type
import java.util.UUID
import javax.persistence.Column
import javax.persistence.GeneratedValue
import javax.persistence.Id

@Id @GeneratedValue
@Type(type ="uuid-char") @Column(length = 36)
private UUID id;


1
2
3
4
5
6
7
@Id
@GeneratedValue(generator ="uuid")
@GenericGenerator(name ="uuid", strategy ="uuid")
@Column(name ="UUID_ID")
public String getId(){
return id;
}

这是在Hibernate 5.0.11.FINAL中对uuid生成器使用批注的正确方法。

注意:不建议使用IT。