【问题标题】:How to use UUIDs with Hibernate as a field?如何将 UUID 与 Hibernate 一起用作字段?
【发布时间】:2014-03-03 14:32:21
【问题描述】:

我正在尝试使用不带@Id 注释的生成的 UUID,因为我的主键是别的东西。应用程序不生成 UUID,你有什么想法吗?

这是我的声明:

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

我正在使用带有 Oracle10g 的 Hibernate 4.3.0。

【问题讨论】:

  • 您找到解决方案了吗?我也遇到了同样的问题。
  • 我使用最后一个答案作为修复
  • @FlorianMozart 你应该接受最后一个答案

标签: java hibernate uuid


【解决方案1】:

查看GeneratedValue的Javadoc:

提供主键值的生成策略规范。

换句话说 - 仅使用注释来初始化“无 ID”属性是不可能的。

但是你可以使用@PrePersist:

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

【讨论】:

    【解决方案2】:

    试试这个可能有帮助

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

    阅读这个link阅读hibernate文档是可能的

    【讨论】:

    • 我使用了没有@Id 注释的解决方案。没有改善:/
    • @Engineer - 您应该为您的答案添加更多解释。链接可能会过时。引用来源绝对合适,但您应该提供适当、完整的回复。
    • Unable to build Hibernate SessionFactory: Caused by: org.hibernate.AnnotationException: Unknown Id.generator: hibernate-uuid
    • 没有@Id注释就不能生成它。我不希望我的列成为主键。
    • 这不能回答问题。
    【解决方案3】:

    这并不是因为您的 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 来管理 UUID。感谢您的帮助
    • Hibernate 什么都不做来防止 ID - 冲突(特别是如果数据库中已经存在第一个值,它不会生成新值)
    猜你喜欢
    • 1970-01-01
    • 2016-02-10
    • 1970-01-01
    • 1970-01-01
    • 2021-07-24
    • 1970-01-01
    • 2023-03-23
    • 1970-01-01
    相关资源
    最近更新 更多