简体   繁体   中英

Getting not-null errors despite having a default value set.

I have the following database column:

 `last_modified` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP

With the following mapping in hibernate:

@Temporal(TemporalType.TIMESTAMP)
@Column(name="last_modified", nullable=false, length=19)
public Date getLastModified() {
    return this.lastModified;
}

This has been working fine for months now but all of a sudden out of nowhere I am getting the following error:

javax.persistence.PersistenceException: org.hibernate.PropertyValueException: not-null property references a null or transient value: com.fs.model.BrowserHistory.lastModified

So I am wondering, why is this happening all of a sudden? Is it OK if I set the lastModified field to be nullable?

Looks like you would like to record the modification timestamp. To avoid setting it manually (or not setting it and getting errors) you can use lifecycle callbacks:

@PrePersist
public void updateTimestamps() {
    lastModified = new Date();
}

I found out that database generated columns need some specific annotations:

@Column(name="last_modified", nullable=false, length=19, insertable=false, updatable=false)
@Generated(GenerationTime.ALWAYS)

We are trying this out now but I think it will fix the issue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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