3

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.

Sal Velazquez
  • 189
  • 2
  • 11
  • Could you post your table DDL? The `columnDefinition` is used when hibernate generates the database for you, if you use liquibase for instance the DDL must not necessary match. – Andreas Sep 14 '17 at 20:02
  • Apologies. I forgot to mention that hibernate is not set to generate the database for me. Just to validate that the existing database works with my entities. – Sal Velazquez Sep 14 '17 at 20:42

5 Answers5

1

This is another way for a create timestamp in spring:

@CreationTimestamp
@Column(name = "create_timestamp")
private Date createTimestamp;
Jan Wytze
  • 3,307
  • 5
  • 31
  • 51
0

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.

slilie
  • 1
  • 1
0

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

Andreas
  • 5,251
  • 30
  • 43
0

It is another solution ...!!!

@CreationTimestamp
private LocalDateTime createTime;


@UpdateTimestamp
private LocalDateTime updateTime;

Don't Forget the use.. !!

" @EntityListeners(AuditingEntityListener.class) "

Use like this --

It is just Entity

0
import org.hibernate.annotations.CreationTimestamp;



@CreationTimestamp
@Column(name = "created_at", updatable = false)
private Date createAt;
Sai Vamsi
  • 101
  • 5