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
所以我想切换到
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; |
它应该是
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中用
这将使用UUID v4,并且自动生成的uuid将像通常
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 |
在当前的5.4.2 Hibernate版本中,
如果要在数据库表中使用人类可读的varchar(36)字段,
而且您的Java类中还有一个可序列化的UUID数据类型,
您可以在使用
请注意,
请注意,对于PostgreSQL,您应该改用
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。