Reputation: 199
I have an entity with the field called createTimestamp. This is created by the database when it is inserted. The getter looks like this:
@Column(name = "create_timestamp", columnDefinition = "TIMESTAMP DEFAULT CURRENT_TIMESTAMP", insertable = false)
public ZonedDateTime getCreateTimestamp() {
return createTimestamp;
}
However, when my service calls the dao (spring repository) to create the entity, the create timestamp is null.
My dao method to create:
@Override
public int insert(AntennaSpec antennaSpec) {
super.save(antennaSpec);
logger.info("Antenna Spec " + antennaSpec.getAntennaCode() + " created");
return antennaSpec.getAntennaSpecId();
}
My REST resource class calls the service to create the entity by calling the create method. The method returns the id of the newly created entity. In the resource, I then call my service to return the entity passing the id and yet the create timestamp is null. What i have done to get this to populate is in my resource, i've detached the entity and then fetch the entity again. That works but I don't like exposing detach
to my service or resource classes.
Any help would be appreciated.
Upvotes: 3
Views: 3536
Reputation: 111
import org.hibernate.annotations.CreationTimestamp;
@CreationTimestamp
@Column(name = "created_at", updatable = false)
private Date createAt;
Upvotes: 0
Reputation: 69
It is another solution ...!!!
@CreationTimestamp
private LocalDateTime createTime;
@UpdateTimestamp
private LocalDateTime updateTime;
Don't Forget the use.. !!
" @EntityListeners(AuditingEntityListener.class) "
Use like this --
Upvotes: 0
Reputation: 5319
columnDefinition
has only an effect if you let hibernate generate the database; otherwise it is just ignored. Just alter your column via your database migration tool to the desired state.
columnDefinition
(Optional) The SQL fragment that is used when generating the DDL for the column. JPA JavaDoc
Upvotes: 0
Reputation: 1
It looks like you might want to add the annotation @Temporal(TemporalType.TIMESTAMP)
to your column as discussed in the answer given here.
Look here for additional information on how persist, save, update, merge and saveOrUpdate perform differently for different object states.
Upvotes: 0
Reputation: 3497
This is another way for a create timestamp in spring:
@CreationTimestamp
@Column(name = "create_timestamp")
private Date createTimestamp;
Upvotes: 1