Hibernate强制时间戳以持久/加载为UTC [英] Hibernate force timestamp to persist/load as UTC

查看:152
本文介绍了Hibernate强制时间戳以持久/加载为UTC的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用java,mysql,hibernate(3.6.x)。
在java端我使用java.sql.Timestamp对象。
在mysql端,我使用的是datetime列。

我希望休眠时使用UTC时区保存/加载这些Timestamp对象,无论system / java / mysql时区。



我发现如何使用JPA和Hibernate在UTC时区存储日期/时间和时间戳这是提供信息的,但缺少一些我正在努力寻找的最终实现信息。



我想实现一个UtcTimestampTypeDescriptor,如该线程所示,并配置hibernate使用它来代替正常的TimestampTypeDescriptor。



我怎样才能配置hibernate使用UtcTimestamp类型而不是默认的Timestamp类型?

解决方案

实现自定义Hibernate类型的另一种方法是添加在JDBC连接URL中使用JDBC选项:

  useTimezone = true 
serverTimezone = UTC

这会强制您的JDBC连接进入UTC时区并要求MySQL执行转换来自JVM时区。最终结果是,您可以在JVM上保留本地时区(例如用于打印日志消息等),而DATETIME列将保持为UTC。



例如:

 < bean id =hibernateAnalysisSessionFactoryclass =org.springframework.orm.hibernate4.LocalSessionFactoryBean> 
< property name =hibernateProperties>
<道具>
<! - 连接参数 - >
< prop key =hibernate.connection.driver_class> com.mysql.jdbc.Driver< / prop>
< prop key =hibernate.connection.url> jdbc:mysql:// hostname / databaseName?useTimezone = true& amp; amp; amp; amp; amp; amp; amp; amp; amp; amp; amp; amp; amp; amp; amp; amp; amp; amp; amp; amp; amp; amp; amp; amp; amp; amp; amp; amp; amp; amp; amp;
...


I'm using java, mysql, hibernate (3.6.x). On the java side I'm using java.sql.Timestamp objects. On the mysql side I'm using datetime columns.

I want hibernate to save/load these Timestamp objects using UTC time zone regardless of system/java/mysql time zone.

I found " How to store date/time and timestamps in UTC time zone with JPA and Hibernate " which was informative but lacking some final implementation info which I'm struggling to find.

I want to implement a UtcTimestampTypeDescriptor as shown in that thread and configure hibernate to use this instead of the normal TimestampTypeDescriptor.

How can I configure hibernate to use the UtcTimestamp type instead of the default Timestamp type?

解决方案

An alternative to implementing custom Hibernate types is to add the following JDBC options to your JDBC connection URL:

useTimezone=true
serverTimezone=UTC

This will force your JDBC connection into the UTC timezone and ask MySQL to perform conversions from the JVM timezone. The net effect is that you can keep a local timezone on your JVM (e.g. for printing out log messages and so forth), while DATETIME columns will be persisted as UTC.

For example:

<bean id="hibernateAnalysisSessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
    <property name="hibernateProperties">
        <props>
            <!-- Connection parameters -->
            <prop key="hibernate.connection.driver_class">com.mysql.jdbc.Driver</prop>
            <prop key="hibernate.connection.url">jdbc:mysql://hostname/databaseName?useTimezone=true&amp;serverTimezone=UTC</prop>
            ...

这篇关于Hibernate强制时间戳以持久/加载为UTC的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆