Reputation: 7398
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.
Upvotes: 3
Views: 1130
Reputation: 3227
@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
Upvotes: 0
Reputation: 6686
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
Upvotes: 1