如何在Hibernate中将UUID用作字段?

19

我想在没有@Id注解的情况下使用生成的UUID,因为我的主键是其他东西。 该应用程序不会生成UUID,你有什么想法?

这是我的声明:

@Column(name = "APP_UUID", unique = true)
@GeneratedValue(generator="system-uuid")
@GenericGenerator(name="system-uuid", strategy = "uuid")
private String uuid;

我正在使用Hibernate 4.3.0与Oracle10g。


你找到解决方案了吗?我也遇到了同样的问题。 - rand0m86
我使用上一个答案来进行修复。 - Florian Mozart
3个回答

10

请查看 GeneratedValue 的 Javadoc:

提供了为主键值指定生成策略的规范。

换句话说,仅通过注释无法初始化“非 ID”属性。

但您可以使用 @PrePersist

@PrePersist
public void initializeUUID() {
    if (uuid == null) {
        uuid = UUID.randomUUID().toString();
    }
}

6

试试这个,它可能有所帮助。

@Id
@GeneratedValue(generator = "hibernate-uuid")
@GenericGenerator(name = "uuid", strategy = "uuid2")
@Column(name = "uuid", unique = true)
private String uuid;

阅读此链接中的Hibernate文档, 是可能的.


1
我使用了您的解决方案,但没有使用@Id注释。没有改进 :/ - Florian Mozart
Eclipse 抛出错误:"此类具有复合主键。必须使用 ID 类。" - Florian Mozart
2
@工程师 - 你应该在你的回答中添加更多的解释。链接可能会过时。引用来源是绝对合适的,但你应该提供一个适当、完整的回复。 - Olimpiu POP
1
Unable to build Hibernate SessionFactory: Caused by: org.hibernate.AnnotationException: Unknown Id.generator: hibernate-uuid - EpicPandaForce
3
不加@Id注释是否可以生成它?我不想让我的列成为主键。 - Obaid Maroof
2
这并没有回答问题。 - dryleaf

2

即使你的UUID是主键,也不一定要使用@GeneratedValue进行注释。

例如,您可以这样做:

public class MyClass
{
   @Id
   private String uuid;

   public MyClass() {}

   public MyClass (String uuid) {
      this.uuid = uuid;
   }
}

在您的应用中,在保存实体之前生成一个UUID:
String uuid = UUID.randomUUID().toString();
em.persist(new MyClass(uuid)); // em : entity manager

我知道UUID重复的概率非常小,但是这种情况确实可能发生。这就是为什么我希望Hibernate来管理UUIDs。谢谢你的帮助。 - Florian Mozart
Hibernate没有任何措施来防止ID冲突(特别是如果第一个值已经存在于数据库中,它不会生成新的值)。 - Tobias Liefke

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接