What time zone does Hibernate use when it reads and writes a Java Calendar object to an SQL TIMESTAMP?

前端 未结 4 2199
青春惊慌失措
青春惊慌失措 2020-12-15 06:08

When Hibernate writes a Java Calendar object to an SQL TIMESTAMP column, to which time zone does it adjust the date, that of the computer or that specified in the c

4条回答
  •  星月不相逢
    2020-12-15 06:21

    I just spent 6 hours on a similar issue and thought I would document it here. Hibernate indeed does use the JVM timezone but it can be changed by extending the CalendarType like this:

    public class UTCCalendarType extends CalendarType {
    
        private static final TimeZone UTC = TimeZone.getTimeZone("UTC");
    
        /**
         * This is the original code from the class, with two changes. First we pull
         * it out of the result set with an example Calendar. Second, we set the new
         * calendar up in UTC.
         */
        @Override
        public Object get(ResultSet rs, String name) throws SQLException {
            Timestamp ts = rs.getTimestamp(name, new GregorianCalendar(UTC));
            if (ts != null) {
                Calendar cal = new GregorianCalendar(UTC);
                cal.setTime(ts);
                return cal;
            } else {
                return null;
            }
        }
    
        @Override
        public void set(PreparedStatement st, Object value, int index) throws SQLException {
            final Calendar cal = (Calendar) value;
            cal.setTimeZone(UTC);
            st.setTimestamp(index, new Timestamp(cal.getTime().getTime()), cal);
        }
    }
    

    the secret sauce here is :

      rs.getTimestamp(name, new GregorianCalendar(UTC));
    

    This converts the timezone from the result set to whatever timezone you want. So what I did was use this type with any UTC calendars and the standard Hibernate type for the local time. Works slick as a whistle...

提交回复
热议问题