简体   繁体   中英

Hibernate @UpdateTimestamp annotation usage

I am using Hibernate core 5.4.22 and Hibernate common annotations 5.1.2. I have tried to save the update timestamp on the DB entry using the following annotation:

@UpdateTimestamp
private LocalDateTime closedDateTime;

Unfortunately, this works only when creating a new entry in the DB but not when updating the entry row.

According to the hibernate documentation :

The @UpdateTimestamp annotation instructs Hibernate to set the annotated entity attribute with the current timestamp value of the JVM when the entity is being persisted.

The supported property types are:

  • java.util.Date
  • java.util.Calendar
  • java.sql.Date
  • java.sql.Time
  • java.sql.Timestamp

You use direct update query, but the @UpdateTimestamp annotation does not work for this case.

Imagine you have the TestData entity:

@Entity
public class TestData
{
   @Id
   private Long id;

   private String name;

   @UpdateTimestamp
   private LocalDateTime time;
}

So, you can create new entity in the following way:

TestData testData = new TestData();
testData.setId(1L);
testData.setName("Name 1");
entityManager.persist(testData);

or update existing entity in the following way:

TestData testData = entityManager.find(TestData.class, 1L);
testData.setName("Name 11");
testData = entityManager.merge(testData);

in the last case hibernate will update the time field automatically by the following query:

13:00:32,468 DEBUG SQL:144 - // update com.test.hibernate.entities.TestData 
update  TEST_SCHEMA.TST_TEST_DATA 
set
   name=?,
   time=? 
where
   id=?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM