When upgrading from Hibernate 4 to 5, Calendar objects from a other timezones are saved differently. Can Hibernate 5 be configured to behave the same way Hibernate 4 did?
ex.
- MySQL column datatype: datetime
- Computer Timezone: US/Eastern
- Computer Time: 2021-04-28 22:17:51
- Calendar object Timezone: Canada/Pacific
- Using Hibernate 4, this saves in a MySQL database as: 2021-04-28 22:17:51
- Using Hibernate 5, this saves in a MySQL database as: 2021-04-28 19:17:51 (Note that it saved the timezone's time)
There is a Hibernate task that may explain this: HHH-7375 and commit
In Hibernate 5, this happens whether or not the object is annotated with @Temporal(TemporalType.TIMESTAMP)
Object class
@Entity
public class TimeTestObj {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
Integer id;
@Temporal(TemporalType.TIMESTAMP) // Happens whether or not this is set
Calendar calendar;
public TimeTestObj(Calendar calendar) {
this.calendar = calendar;
}
}
Sample Scenario
public class TimeTest {
public static void main(String[] args) {
SessionFactory sessionFactory = buildSessionFactory();
// NOTE that the computer is in US/Eastern timezone
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("Canada/Pacific"));
TimeTestObj timeTestObject = new TimeTestObj(calendar);
Session session = sessionFactory.getCurrentSession();
Transaction trans = session.beginTransaction();
session.saveOrUpdate(timeTestObject);
trans.commit();
sessionFactory.close();
}
private static SessionFactory buildSessionFactory() {
Configuration configuration = new Configuration();
configuration.addAnnotatedClass(TimeTestObj.class);
configuration.configure();
//For hibernate 4.0+
//ServiceRegistryBuilder srb = new ServiceRegistryBuilder().applySettings(configuration.getProperties());
//ServiceRegistry serviceRegistry = srb.buildServiceRegistry();
//For hibernate 5
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
return configuration.buildSessionFactory(serviceRegistry);
}
}