Home > Enterprise >  Hibernate retrieve timestamps in UTC
Hibernate retrieve timestamps in UTC

Time:01-13

I am using hibernate spring and want to store/load timestamps in UTC. I've read that I should add a property, so I added this to my application.properties

spring.jpa.properties[hibernate.jdbc.time_zone]=UTC

This worked for one part of the problem - now dates are saved in utc in the database. But when I retrieve timestamps, they are transformed into default timezone. How can I fix this without setting default time zone to UTC? The property of the entity has type LocalDateTime. I ran the code, and noticed that the proper result set method is used during get(the one that accepts calendar) with instance that has zone info storing UTC. But after setting calendar's values to the one retrieved from the database, the calendar is transformed into Timestamp with this code

Timestamp ts = new Timestamp(c.getTimeInMillis());

In debug mode, I see that ts stores cdate field with value of timestamp in default time zone(not UTC).

CodePudding user response:

we can also set it up` per-session basis:

session = HibernateUtil.getSessionFactory().withOptions()
  .jdbcTimeZone(TimeZone.getTimeZone("UTC"))
  .openSession();

CodePudding user response:

My database timezone was in UTC and in my application timezone I solved this problem by having both the Entity and the table have a date in UTC so that there will need to be no conversion between them. Then I did the conversions between timestamps in code in the getters and setters. Then I think you do it manually.

Setter and getter for that field:

public void setCreatedDate(LocalDateTime createdAt)
{         
    this.createdAt = createdAt.atZone(ZoneId.systemDefault()).withZoneSameInstant(ZoneOffset.UTC).toLocalDateTime();
}

public LocalDateTime getCreatedDate()
{         
    return createdAt.atZone(ZoneId.systemDefault()).withZoneSameInstant(ZoneOffset.UTC).toLocalDateTime();
}
  • Related