Hibernate force timestamp to persist/load as UTC [duplicate]

◇◆丶佛笑我妖孽 提交于 2019-12-18 12:15:00

问题


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?


回答1:


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

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>
            ...



回答2:


get class public class UtcTimestampType extends TimestampType from your link
and make this code

@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



来源:https://stackoverflow.com/questions/9823411/hibernate-force-timestamp-to-persist-load-as-utc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!