休眠强制时间戳以保持/加载为 UTC

2022-01-13 00:00:00 timestamp timezone mysql java Hibernate

我正在使用 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&amp;serverTimezone=UTC</prop>
            ...

相关文章