gpt4 book ai didi

java - PostgresQL 和 Hibernate 自动生成(不是 PK)值

转载 作者:行者123 更新时间:2023-12-01 16:24:02 31 4
gpt4 key购买 nike

当我保存在数据库中时,我尝试自动生成不是 PK 的值。我创建了具有值(value)的实体:

class Entity {    

// Other values

@NaturalId
@SequenceGenerator(name = "number_sequence", sequenceName =
"number_sequence")
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "number_sequence")
private Long number;
}

以及序列脚本:

CREATE SEQUENCE schema.number_sequence AS BIGINT
INCREMENT 1
START 1
OWNED BY table_name.number;

但是当我构建没有 number 的实体并将其保存到数据库时,出现错误:

org.postgresql.util.PSQLException: ERROR: null value in column "number" violates not-null 
constraint
Detail: Failing row contains (e925b4fb-5147-4754-b949-08d79a6ad764, 2020-06-04
14:31:50.49584+03, null, bd765ef29c3211e98b6b019787d6f1ee,
1e100b1da97b11e98b6b511f0c71b787).

我哪里错了?

最佳答案

感谢 Kayaman 和 SternK。我做了什么:

 @NaturalId
@Generated(value = GenerationTime.INSERT)
@Column(insertable = false, updatable = false)
private Long number;

在我的实体上以及:

CREATE SEQUENCE number_sequence AS BIGINT
INCREMENT 1
START 1
OWNED BY table.number;

ALTER TABLE table
ALTER COLUMN number SET DEFAULT nextval('number_sequence');

在我的实体中。如果上面的查询不起作用,您可以添加 schema.number_seq 或 schema.table

关于java - PostgresQL 和 Hibernate 自动生成(不是 PK)值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62193756/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com