Home > Software engineering >  can JPA datetime column be automatically set on saving?
can JPA datetime column be automatically set on saving?

Time:07-02

Assume there is an entity like below:

@Entity
class MyEntity{
  private Integer myValue;
  private LocalDateTime time;
}

and the time is not exactly update time.

Sometime the record is handled like this:

myEntity.setMyValue(10);
myEntity.save();

and also this happens,

myEntity.setMyValue(11);
myEntity.setTime(LocalDateTime.now());
myEntity.save();

but I wonder if there is an alternative way to express the query like below

UPDATE my_entity SET time = now() 

I know an annotation @LastModifiedDate but this time I can't use it..

CodePudding user response:

You may place the @Column annotation over the time field in your entity and then specify a default value:

@Entity
class MyEntity {
    private Integer myValue;

    @Column(name="time", columnDefinition="DATETIME DEFAULT NOW()")
    private LocalDateTime time;
}

Note that the above assumes that you are using MySQL which uses NOW() for the current datetime. This would have to change depending on your database, so this approach has some tight coupling between your application and the underlying database.

You could also define a default value directly on your database.

CodePudding user response:

You can use lifecycle events. You can add this method to your entity :

@PrePersist
@PreUpdate
public void saveTime() {
  if(this.time == null) {
    this.time = LocalDateTime.now();
  }
}
  • Related