Hibernate force timestamp to persist/load as UTC(休眠强制时间戳以保持/加载为 UTC)
问题描述
我正在使用 java、mysql、hibernate (3.6.x).在 java 方面,我使用 java.sql.Timestamp 对象.在 mysql 方面,我使用的是日期时间列.
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.
我希望 hibernate 使用 UTC 时区保存/加载这些 Timestamp 对象,而不考虑系统/java/mysql 时区.
I want hibernate to save/load these Timestamp objects using UTC time zone regardless of system/java/mysql time zone.
我发现如何以 UTC 存储日期/时间和时间戳JPA 和 Hibernate 的时区",它提供了丰富的信息,但缺少一些我正在努力寻找的最终实现信息.
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.
我想实现一个 UtcTimestampTypeDescriptor,如该线程中所示,并将休眠配置为使用它而不是普通的 TimestampTypeDescriptor.
I want to implement a UtcTimestampTypeDescriptor as shown in that thread and configure hibernate to use this instead of the normal TimestampTypeDescriptor.
如何将休眠配置为使用 UtcTimestamp 类型而不是默认的 Timestamp 类型?
How can I configure hibernate to use the UtcTimestamp type instead of the default Timestamp type?
推荐答案
仅适用于 MySQL,实现自定义 Hibernate 类型的替代方法是将以下 JDBC 选项添加到 JDBC 连接 URL:p>
For MySQL only, an alternative to implementing custom Hibernate types is to add the following JDBC options to your JDBC connection URL:
useTimezone=true
serverTimezone=UTC
这将强制您的 JDBC 连接到 UTC 时区,并要求 MySQL 从 JVM 时区执行转换.最终效果是您可以在 JVM 上保留本地时区(例如,用于打印日志消息等),而 DATETIME 列将保留为 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.
例如:
<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>
...
这篇关于休眠强制时间戳以保持/加载为 UTC的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:休眠强制时间戳以保持/加载为 UTC
基础教程推荐
- 在 Java 中创建日期的正确方法是什么? 2022-01-01
- 不推荐使用 Api 注释的描述 2022-01-01
- 大摇大摆的枚举 2022-01-01
- Java Swing计时器未清除 2022-01-01
- 如何在 JFrame 中覆盖 windowsClosing 事件 2022-01-01
- 验证是否调用了所有 getter 方法 2022-01-01
- 如何在 Spring @Value 注解中正确指定默认值? 2022-01-01
- Java 实例变量在两个语句中声明和初始化 2022-01-01
- 从 python 访问 JVM 2022-01-01
- 多个组件的复杂布局 2022-01-01
