Spring 引导实体中自动生成的唯一键

Unique key auto generated in Spring Boot Entity

我的实体 table 中有一个主键,它是自动生成的,但现在我希望自动生成唯一键,那么该怎么做 请帮帮我。

    @Entity
    @Table(name = "director")
    public class Director {
    
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        @Column(name = "id")
        private long id;
    
//how to make this field auto generated like above one
        @Column(name = "subid", unique=true)
        private long sub_id;

我的数据库table图片在这里请参考

您可以使用时间戳或 static AtomicLong 计数器作为 sub_id 值。尝试在您的实体 class 中定义带有注释 @PrePersist 的方法,您的 JPA 提供程序将在持久化对象之前执行它。
注意:在并发环境中使用时间戳可能会导致冲突,并且值不会是唯一的。

private final static AtomicLong subIdCounter = new AtomicLong(System.nanoTime());

@PrePersist
void sub_id() {
    this.sub_id = subIdCounter.incrementAndGet();
}

经过短暂的研究,Hibernate 似乎只支持用 @Id 注释的字段生成值的特性。使用 @Id 和默认 @generatedValue Hibernate 创建 - 根据使用的数据库和方言 - 适当的方式来生成 id 字段的值。通常这类似于创建 sequence 并设置列定义(示例来自 Postgres 12 ):

id bigint not null nextval('director_id_seq'::regclass)

有趣的是,这是通过发出这样的创建语句来完成的:

create table director (id bigserial not null, primary key (id))

因此,列类型bigserial实际上生成了用于将默认值插入id列的序列。

您想要为列 sub_id 生成值的选项有两个,因为它生成到列 id.两者都依赖于数据库。

只需将序列手动创建到数据库并更改列 sub_id 以从序列中获取默认值。

更改您的列定义以使用适当的列类型,例如:

@Column(name = "subid", insertable = false,
        nullable = false, unique = true, columnDefinition = "bigserial")
private long sub_id;

这将导致 Hibernate 生成 table 如:

create table director (id bigserial not null, subid bigserial not null, primary key (id))

结果列如下:

subid bigint not null nextval('director_subid_seq'::regclass)

但是再说一次:这是特定于数据库的东西。

另请注意:JPA 仅知道存储到 id 字段的值。 subid 被插入到数据库 table 但 sub_id 字段直到实体在其持久性上下文中刷新后才被填充。