通过注释使用Hibernate UUIDGenerator

| 我正在按以下方式使用我的uuid:
@Id
@GeneratedValue(generator = \"uuid\")
@GenericGenerator(name = \"uuid\", strategy = \"uuid\")
@Column(name = \"uuid\", unique = true)
private String uuid;
但我收到了一个聪明的Hibernate警告:   使用   org.hibernate.id.UUIDHexGenerator   不会生成IETF RFC 4122   符合的UUID值;考虑使用   org.hibernate.id.UUIDGenerator代替 所以我想切换到
org.hibernate.id.UUIDGenerator
,现在我的问题是如何将其告知Hibernate的生成器。我看到有人用它作为\“ hibernate-uuid \”-所以这是我尝试过的方法,但是结果是负面的:
@Id
@GeneratedValue(generator = \"hibernate-uuid\")
@GenericGenerator(name = \"hibernate-uuid\", strategy = \"hibernate-uuid\")
@Column(name = \"uuid\", unique = true)
private String uuid;
    
已邀请:
        应该是
uuid2
...
@GenericGenerator(name = \"uuid\", strategy = \"uuid2\")
...
见5.1.2.2.1。各种其他发电机。     
        HibernateDoc说您可以使用以下内容:
@Id
@GeneratedValue(generator=\"system-uuid\")
@GenericGenerator(name=\"system-uuid\", strategy = \"uuid\")
@Column(name = \"uuid\", unique = true)
private String uuid;
我希望您正在使用Hibernate 3.5。     
        尝试...
@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,则下面的代码就足够了:
@Id 
@GeneratedValue
private java.util.UUID id;
在MySQL中将
id
列的类型定义为type9ѭ,或者在其他SQL实现中等效。     
           未知的ID生成器:hibernate-uuid
@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;
}
    
        这将使用UUID v4,并且自动生成的uuid将像通常的“ 11”一样存储在列中:
@Id
@GeneratedValue(generator = \"uuid2\")
@GenericGenerator(name = \"uuid2\", strategy = \"uuid2\")
@Column(length = 36)
private String uuid;
这应该会对性能产生一些影响: 消耗的尺寸大于
BINARY(16)
水化后,“ 14”实例比“ 15”实例消耗更多的内存:作为字符串的UUID为112字节,而对于“ 16”实例则为32字节(即两个long和obj标头)。 但是,使用基于字符串的UUID更加容易-编写查询更容易,并且您可以看到表的内容。 在Hibernate 5.3上测试     
        在当前的5.4.2 Hibernate版本中, 如果要在数据库表中使用人类可读的varchar(36)字段, 而且您的Java类中还有一个可序列化的UUID数据类型, 您可以在使用
java.util.UUID
类型声明字段成员的同时使用
@Type(type = \"uuid-char\")
。 注意,在MySQL中,将字段长度从255减少到36时,ѭ19很重要。 请注意,在PostgreSQL中,您应该改用
@Type(type = \"pg-uuid\")
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;
    
        
@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。     

要回复问题请先登录注册