简体   繁体   English

JPA / Hibernate CreationTimestamp 不适用于 PrimaryKeyJoinColumn

[英]JPA / Hibernate CreationTimestamp not working with PrimaryKeyJoinColumn

I am trying to use the @CreationTimestamp to automatically set the created date of the new entity, but it doesn't seem to be working from some reason.我正在尝试使用@CreationTimestamp自动设置新实体的创建日期,但由于某种原因它似乎不起作用。

ERROR: null value in column "created_at" violates not-null constraint

In the entity I have defined the annotation like this.在实体中,我定义了这样的注释。

@CreationTimestamp
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "CREATED_AT", nullable = false)
private Date createdAt;

Liquibase migration file: Liquibase 迁移文件:

<property name="date.type" value="TIMESTAMP WITH TIME ZONE" dbms="postgresql" />

<createTable tableName="USER">
    <column name="ID" type="${uuid_type}"><constraints nullable="false"/></column>
    <column name="CREATED_AT" type="${date.type}"><constraints nullable="false"/></column>
</createTable>

And the way I'm persisting the entity.以及我坚持实体的方式。

@Transactional(propagation = Propagation.REQUIRED)
public E insert(E e) {
    entityManager.persist(e);
    entityManager.flush();
    return e;
}

The code works when I set the createdAt date manually.当我手动设置createdAt日期时,代码有效。 But it does not generate one automatically what the annotation should do.但它不会自动生成注释应该做什么。 Can anyone point me to why not?!谁能指出我为什么不呢?!

I had the same problem when I was looking for an answer here.当我在这里寻找答案时,我遇到了同样的问题。 This is how I annotated it to make it work:这是我注释它以使其工作的方式:

@CreationTimestamp
@Column(name = "created", nullable = false, updatable = false)
@Temporal(TemporalType.TIMESTAMP)
private Date created;

I think the important part here is that the column is defined as not "updateable" - so the value will not be changed when updating the row.我认为这里的重要部分是该列被定义为不可更新的 - 因此更新行时不会更改该值。 Because if it where "updateable" then JPA wouldn't generate the value.因为如果它是“可更新的”,那么 JPA 就不会生成该值。

However I had the "insertable=false" set as well which was wrong, because then JPA tried to persist it with a null value which throws an error because the column is set to be NOT NULL.但是,我也设置了“insertable=false”,这是错误的,因为随后 JPA 尝试使用空值持久化它,这会引发错误,因为该列设置为 NOT NULL。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM