0

In a Spring Booot app, I need to keep creation date of the content. For this purpose, normally ı would use LocalDateTime, but I think it is better to use Instant as this field is like a timestamp. On the other hand, I have just seen @CreationTimestamp and I am confused about the proper usage.

@CreationTimestamp
private LocalDateTime createdAt;

So, do I need to use @CreationTimestamp for datetime field in Hibernate? Or is it ok using Instant for keeping creation date as shown below in my Entity?

private Instant createdAt;

1 Answers1

1

@CreationTimestamp is a Hibernate annotation that automatically sets the entity creation timestamp to the current time when the entity is persisted to the database. This annotation works with java.util.Date, java.sql.Date, java.sql.Time, java.sql.Timestamp, and java.time.LocalDateTime types. It is equivalent to setting the value using LocalDateTime.now().

If you want to store a timestamp with millisecond precision, then using Instant is a good choice. Instant is a class in the java.time package that represents a point in time, with nanosecond precision, relative to the epoch (January 1, 1970, 00:00:00 UTC).

Therefore, you can use Instant to store the creation date in your entity class as shown below:

private Instant createdAt;

You can set the createdAt field with the current timestamp before persisting the entity to the database by using Instant.now().

MyEntity entity = new MyEntity();
entity.setCreatedAt(Instant.now());
entityManager.persist(entity);

In summary, you can use Instant to store the creation date in your entity class and set it manually, or use @CreationTimestamp to automatically set the creation timestamp in Hibernate. Both approaches are valid, and the choice depends on your use case and preference.

  • Thanks amigo, actually I read most of this part from documentation but could not be sure. –  Feb 24 '23 at 13:43
  • Do you have any idea regarding to mapping in Hibernate? Any comment for https://stackoverflow.com/questions/75557276/bidirectional-manytomany-with-a-link-entity-in-hibernate ? –  Feb 24 '23 at 13:43