Using Hibernate doesn't trigger MySQL's "ON UPDATE CURRENT_TIMESTAMP"

luso :

In a MySQL DB every table has a column updated which is created as

[...] `updated` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,

As expected, every row update does trigger the timestamp's update to the CURRENT_TIMESTAMP. This is true when I update a row via the SQL shell, command line, DBeaver, Workbench BUT

Working with Hibernate (Spring Boot 2, Spring Data JPA) does not work. I mean, pseudocode such as:

[Tx]
entity = repository.findById(1) --> Returns my entity with updated == 1L 
entity.setProperty("other value")
repository.save(entity)
[/Tx]

At this point, the DB entry has been updated ("other value" is the current value) but the updated column is still 1L where should be CURRENT_TIMESTAMP

I used to bypass this problem either

  • annotating the property as @UpdateTimestampor h
  • annotating a method with @PrePersist && @PreUpdate which would programatically set the current timestamp before the UPDATE SQL statement

The problem with both approaches is that I don't have the updated value until out of my Tx:

[Tx]
entity.getUpdated() == 1L
entity.setName("other")
repository.save(entity) // at this point the updated is still == 1L
repository.findById()  // at this point the updated is still == 1L
[/Tx]

[Tx]
repository.findById()  // good timestamp value
[Tx]

Is it normal that MySQL doesn't trigger the update in the first place?

Is there a way to fetch the updated value in the same transaction?

Kayaman :

You need JPARepository.saveAndFlush() (or with raw JPA, EntityManager.refresh()) to get the updated value from the database in the same transaction. This affects all database generated values.

JPA doesn't know that values are changing inside the database, and it would be bad for performance to always re-read the saved value. That's why in a new transaction you get the correct values, as the data is actually fetched from the database. In the same transaction the value is still in memory and assumed to be unchanged.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=322742&siteId=1