Home » Java » java – SQL row creation and modification time set by database or ORM?-Exceptionshub

java – SQL row creation and modification time set by database or ORM?-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment

Questions:

If I want to track the created_at and modified_at timestamp of a mysql row, there are two ways.

Let mysql update the fields:

@Column(insertable = false, updatable = false,
       columnDefinition = "TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP")
private LocalDateTime create_at;

Or use the orm (hibernate) I’m using with spring-jpa:

@CreationTimestamp //or even the jpa @CreatedAt
@Temporal(TemporalType.TIMESTAMP)
private Date modification;

Question: what is the advantage of one over the other.
Advantage of orm approach is independence of the database type (could be important eg for unit tests). But also the orm has to “intercept” the persist process for it.

With the CURRENT_TIMESTAMP the row is independent of the executing code.

Is there any clear line when to chose which approach?

How to&Answers:

The main disadvantage of the database approach is that you end with a column definition that is database dependent.

But, there is a subtle diference using the ORM approach, is that you can know the assigned value in the same method/transaction. While with the data base approach you will not know the vaule generated until you do another query.