【问题标题】:PostgresQL and Hibernate Auto Generated (not PK) valuePostgresQL 和 Hibernate 自动生成(不是 PK)值
【发布时间】:2020-06-04 11:41:29
【问题描述】:

当我保存在数据库中时,我尝试自动生成不是 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 的情况下构建实体并将其保存到数据库时出现错误:

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

我哪里错了?

【问题讨论】:

  • 这能回答你的问题吗? Hibernate JPA Sequence (non-Id)
  • 在db中将列设置为NOT NULL DEFAULT NEXTVAL('number_sequence')
  • 我看到了这个答案,但我不想再为唯一的价值生成创建一个实体。也许还有其他方法可以做到这一点。
  • Kayaman,不,我没有,但我会尽力让你知道
  • 也许this 会有所帮助。

标签: java postgresql hibernate


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2022-08-18
    • 2013-08-13
    • 2013-10-05
    • 1970-01-01
    • 1970-01-01
    • 2012-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多