PostgreSQL 默认值在 Spring/Hibernate 应用程序中不起作用

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

Spring/Hibernate 上有一个应用程序。我正在使用 PostgreSQL 数据库。我用这个脚本创建了表:

create table competence_aud
(
    ctl_validfrom     timestamp(6) not null default current_timestamp,
    pk                int8,
    employee          int8,
    competence        int8,
    lastupdatedwhen   timestamp(6)
);

我假设,如果日期为 NULL,那么当前日期将被插入到表中(因为我使用

current_timestamp
)。

然后,在我创建这个类的代码中:

@Entity
@Data
@NoArgsConstructor
@AllArgsConstructor
@Table(name = "competence_aud")
@SourceEntity(schema = Schemas.core, table = "competence")
public class CompetenceAudEntity implements Record<Long> {

    @Id
    @Column(name = "pk")
    private long pk;

    @Column(name = "ctl_validfrom")
    private Timestamp ctlValidfrom;

    @Column(name = "employee")
    private Long employee;

    @Column(name = "competence")
    private Long competence;

    @Column(name = "lastupdatedwhen")
    private Timestamp lastupdatedwhen;

    @Override
    public Long getObjectId() {
        return pk;
    }

    public void setLastupdatedwhen(Timestamp lastupdatedwhen) {
        this.lastupdatedwhen = lastupdatedwhen;
        this.ctlValidfrom = lastupdatedwhen;
    }

}

我启动应用程序。在这种情况下,当我得到日期的 NULL 值时,我在日志中看到错误:

o.h.engine.jdbc.spi.SqlExceptionHelper   : ERROR: null value in column "ctl_validfrom" of relation "competence_aud" violates not-null constraint
  Detail: Failing row contains (null, 22, 474, 546, null).

我认为,

current_timestamp
根本不起作用:-(
你能解释一下为什么会发生这种情况吗?我必须如何更改我的代码?

java spring postgresql hibernate
1个回答
0
投票

CompetenceAudEntity
对象插入到表中时,Spring会生成类似以下sql代码:

insert into competence_aud (ctl_validfrom, pk, employee, competence, lastupdatedwhen) values (null, 22, 474, 546, null)

由于 Spring 在

null
字段中显式传递
ctl_validfrom
,因此
current_timestamp
不会触发,也不会自动生成值。

为了解决您的问题,我建议在写入数据库之前生成当前时间。为此,请使用注释

org.hibernate.annotations.CreationTimestamp

示例:

@Entity
@Data
@NoArgsConstructor
@AllArgsConstructor
@Table(name = "competence_aud")
@SourceEntity(schema = Schemas.core, table = "competence")
public class CompetenceAudEntity implements Record<Long> {

    @Id
    @Column(name = "pk")
    private long pk;

    @Column(name = "ctl_validfrom")
    @CreationTimestamp
    private Timestamp ctlValidfrom;

    @Column(name = "employee")
    private Long employee;

    @Column(name = "competence")
    private Long competence;

    @Column(name = "lastupdatedwhen")
    private Timestamp lastupdatedwhen;

   ...

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