Reputation: 551
(1) Why is the "@CreationTimestamp" field updated to null for a "save" called on the repository with a null value for that field? I expect that a field annotated with "@CreationTimestamp" is never updated and maintained only once at the time of creation. But it does not work that way in my current project.
(2) I had to include @Column(updatable =false) (in addition to @CreationTimestamp annotation). Why is this necessary?
Upvotes: 42
Views: 18114
Reputation: 1403
It's 2020, hibernate-core-5.3.12, and still need to set updatable to false.
@CreationTimestamp
@Column(updatable = false)
private LocalDateTime createdDate;
Update
I believe there will be no fix for this because this CreationTimestamp
is from native hibernate package (org.hibernate.annotations
), and I believe the efforts will be on the jpa abstraction (org.springframework.data.annotation.CreatedBy
)
Upvotes: 38
Reputation: 191
1) I faced the same issue on Spring Boot 2.1.2 which uses Hibernate 5.3.7.
I read here that java.util.LocalDateTime
handling was introduced in Hibernate 5.2.3, before that version you had to use one of the following date types:
But it still did not work for me...
So I came up with javax.persistence.PrePersist
annotation:
...
@Column(name = "created_at", updatable = false)
@Temporal(TemporalType.TIMESTAMP)
private Date createdAt;
...
@PrePersist
public void prePersistCreatedAt() {
this.createdAt = new java.util.Date();
}
2) This post discusses that topic and gives decent explanation: Please explain about insertable=false and updatable=false in reference to the JPA @Column annotation.
Also pay attention to the not accepted posts, especially:
Defining insertable=false, updatable=false is useful when you need to map a field more than once in an entity...
Upvotes: 3
Reputation: 2451
@CreationTimestamp is not JPA but just Hibernate.
To create a field automatically with the creation date you can define a property like that:
@Column(name = "creation_date", updatable = false)
@Temporal(javax.persistence.TemporalType.TIMESTAMP)
private Date creationDate = new Date();
Upvotes: 4