PostgresQL和休眠自动生成(非PK)值

时间:2020-06-04 11:41:29

标签: java postgresql hibernate

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

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的情况下构建Entity并将其保存到DB时,出现错误:

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).

我在哪里错了?

1 个答案:

答案 0 :(得分:0)

感谢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