Java Hibernate 强制时间戳以 UTC 格式持久化/加载
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9823411/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Hibernate force timestamp to persist/load as UTC
提问by samz
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.
我正在使用 java、mysql、hibernate (3.6.x)。在 java 方面,我使用 java.sql.Timestamp 对象。在 mysql 方面,我使用的是日期时间列。
I want hibernate to save/load these Timestamp objects using UTC time zone regardless of system/java/mysql time zone.
我希望休眠使用 UTC 时区保存/加载这些 Timestamp 对象,而不管系统/java/mysql 时区。
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.
我发现“如何使用 JPA 和 Hibernate 在 UTC 时区中存储日期/时间和时间戳”,这很有用,但缺少一些我正在努力寻找的最终实现信息。
I want to implement a UtcTimestampTypeDescriptor as shown in that thread and configure hibernate to use this instead of the normal TimestampTypeDescriptor.
我想实现一个 UtcTimestampTypeDescriptor,如该线程中所示,并将休眠配置为使用它而不是普通的 TimestampTypeDescriptor。
How can I configure hibernate to use the UtcTimestamp type instead of the default Timestamp type?
如何配置休眠以使用 UtcTimestamp 类型而不是默认的 Timestamp 类型?
回答by Ilya
get class public class UtcTimestampType extends TimestampType
from your link
and make this code
public class UtcTimestampType extends TimestampType
从您的链接获取课程
并制作此代码
@org.hibernate.annotations.Type(type = "yourPackage.UtcTimestampType")
public java.util.Date date;
using annotations
使用注解
or
或者
<property name="date" column="yourColumn" type="yourPackage.UtcTimestampType" />
using *.hbm.xml
使用 *.hbm.xml
回答by DanJ
For MySQL only, an alternative to implementing custom Hibernate types is to add the following JDBC options to your JDBC connection URL:
对于 MySQL only,实现自定义 Hibernate 类型的替代方法是将以下 JDBC 选项添加到您的 JDBC 连接 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.
这将强制您的 JDBC 连接进入 UTC 时区,并要求 MySQL 从 JVM 时区执行转换。最终效果是您可以在 JVM 上保留本地时区(例如用于打印日志消息等),而 DATETIME 列将保留为 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&serverTimezone=UTC</prop>
...