Reputation: 1282
I have a JPA entity, which contains two column, the createdTime
and modifiedTime
. I'd like to use MySQL's DEFAULT CURRENT_TIMESTAMP
feature to generate the proper time value for this two column, so i write my entity class like:
@Entity
public class Blog {
// ...
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "created_time", updatable = false, insertable = false, nullable = false,
columnDefinition = "datetime default CURRENT_TIMESTAMP")
private Date createdTime;
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "modified_time", updatable = false, insertable = false, nullable = false,
columnDefinition = "datetime default CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP")
private Date modifiedTime;
}
Then i do some experiment on my application, when i check the database, the value of this two column in the database is updated properly.
However, when i check the java entity return by BlogRepository::save
, the value of this two column is not the newest value. For example, when i insert a new Blog
entity, i get null for this two properties on the BlogRepository::save
return value.
I've read some post like https://stackoverflow.com/a/12237110/8510613, understand that if i mark the column as updatable = false
, this situation will happen. So how should i fix this? Simply remove the updatable = false
/insertable = false
seems have no help, but will trigger the column's not null constraint violation. But if i remove the not null constraint on this two column, the value of this two column are just simply null.
Upvotes: 1
Views: 774
Reputation: 13041
You should use @Generated annotation in this case.
2.3.18. Generated properties
Generated properties are properties that have their values generated by the database. Typically, Hibernate applications needed to refresh objects that contain any properties for which the database was generating values. Marking properties as generated, however, lets the application delegate this responsibility to Hibernate. When Hibernate issues an SQL INSERT or UPDATE for an entity that has defined generated properties, it immediately issues a select to retrieve the generated values.
So, you should correct your mapping something like this:
@Temporal(TemporalType.TIMESTAMP)
@Generated(value = GenerationTime.INSERT)
@Column(name = "created_time", updatable = false, insertable = false, nullable = false,
columnDefinition = "datetime default CURRENT_TIMESTAMP")
private Date createdTime;
@Temporal(TemporalType.TIMESTAMP)
@Generated(value = GenerationTime.ALWAYS)
@Column(name = "modified_time", updatable = false, insertable = false, nullable = false,
columnDefinition = "datetime default CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP")
private Date modifiedTime;
Upvotes: 1