如何在 Spring Boot 上使用 Hibernate 生成自动 UUID

问题描述 投票:0回答:6

我想要实现的是生成一个 UUID,该 UUID 在数据库插入期间自动分配。类似于名为“id”的主键列生成一个 id 值。

模型值看起来像这样:

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(nullable = false)
private Long id;


@GeneratedValue(generator = "uuid2")
@GenericGenerator(name = "uuid2", strategy = "uuid2")
@Column(name = "uuid", columnDefinition = "BINARY(16)")
private UUID uuid;

但是当数据库插入完成后。 “uuid”为空。

非常感谢您的帮助。如果我问了一个明显愚蠢的问题,我很抱歉。

hibernate jpa spring-boot uuid
6个回答
28
投票

你可以尝试一下吗?

    @Id
    @GeneratedValue(generator = "uuid2")
    @GenericGenerator(name = "uuid2", strategy = "org.hibernate.id.UUIDGenerator")
    @Column(name = "id", columnDefinition = "VARCHAR(255)")
    private UUID id;

16
投票

u 可以使用 @PrePersist 等一些事件来填充 UUID 字段 https://docs.jboss.org/hibernate/orm/4.0/hem/en-US/html/listeners.html

但是为什么在创建对象时不分配 uuid uuid = UUID.randomUUID() ?


16
投票

框架发生了很多变化,并在 Spring Boot 2.2.5 和 MySQL v5.7 中进行了测试(应该适用于所有 2.0 版本,但需要检查)UUID 可以自动生成,如下所示

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name="id", insertable = false, updatable = false, nullable = false)
private UUID id;

这将以紧凑的方式以二进制格式存储它(有利于存储)。如果由于某种原因需要将 UUID 存储在 Varchar 字段中作为人类可读的(破折号分隔值),可以按如下方式完成

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Type(type="uuid-char")
@Column(name="id", columnDefinition = "VARCHAR(255)", insertable = false, updatable = false, nullable = false)
private String id;

默认情况下,Hibernate 使用二进制格式映射 UUID,因此要更改格式,我们需要使用 Type 注释提供提示。


6
投票

以下对我有用:

@Id
    @GeneratedValue(generator = "UUID")
    @GenericGenerator(
            name = "UUID",
            strategy = "org.hibernate.id.UUIDGenerator"
    )
    @Column(name = "id", updatable = false, nullable = false)
    private UUID id;

0
投票

Hibernate
6.0 开始,您可以只使用注释
@UuidGenerator
。这可用于类型为
UUID
String
的字段。

示例:

@Id
@UuidGenerator
private UUID id;

String

@Id
@UuidGenerator
private String id;

来源:

https://www.baeldung.com/java-hibernate-uuid-primary-key https://docs.jboss.org/hibernate/orm/6.6/javadocs/org/hibernate/annotations/UuidGenerator.html


-1
投票
    @Id
    @GeneratedValue
    private UUID productUUID;

这将在保存实体记录时生成一个随机的uuid

© www.soinside.com 2019 - 2024. All rights reserved.