3

Currently I have a base entity as follows:

@MappedSuperclass
public abstract class BaseEntity {
    @Id
    @GeneratedValue(strategy=GenerationType.SEQUENCE)
    private Long id;
    private boolean deleted;

    @Convert(converter = LocalDateTimePersistenceConverter.class)
    private LocalDateTime createdAt;
    @Convert(converter = LocalDateTimePersistenceConverter.class)
    private LocalDateTime updatedAt;
}

Is it possible to annotate LocalDateTime with something to make database default to current date and time?

p.s. I am not allowed to use hibernate 5.

almeynman
  • 6,708
  • 3
  • 21
  • 31

2 Answers2

1

You could use the @PrePersist annotation.

Executed before the entity manager persist operation is actually executed or cascaded. This call is synchronous with the persist operation.

Example:

  @PrePersist
  protected void onCreate() {
    createdAt = new LocalDateTime();
    updatedAt = new LocalDateTime();
  }

And if you deem it fit you also have available the @PreUpdate annotation.

Read more on events that occur inside hibernate's persistence mechanism

Laurentiu L.
  • 6,368
  • 1
  • 30
  • 57
0

@LaurentiuL is correct.
But I think below should also work

@Convert(converter = LocalDateTimePersistenceConverter.class)
private LocalDateTime createdAt = new LocalDateTime ();
@Convert(converter = LocalDateTimePersistenceConverter.class)
private LocalDateTime updatedAt= new LocalDateTime ();

Also answers of this question should help you : Creation timestamp and last update timestamp with Hibernate and MySQL

Community
  • 1
  • 1
Viraj Nalawade
  • 3,087
  • 3
  • 27
  • 41