新增一个答案,完全基于divestoclimb并得到Shaun Stone的提示。由于这是一个常见问题,并且解决方案有点混乱,所以我想详细说明一下。
这是使用Hibernate 4.1.4.Final版本,不过我认为在3.6之后的任何版本都可以工作。
首先,请创建divestoclimb的UtcTimestampTypeDescriptor。
public class UtcTimestampTypeDescriptor extends TimestampTypeDescriptor {
public static final UtcTimestampTypeDescriptor INSTANCE = new UtcTimestampTypeDescriptor();
private static final TimeZone UTC = TimeZone.getTimeZone("UTC");
public <X> ValueBinder<X> getBinder(final JavaTypeDescriptor<X> javaTypeDescriptor) {
return new BasicBinder<X>( javaTypeDescriptor, this ) {
@Override
protected void doBind(PreparedStatement st, X value, int index, WrapperOptions options) throws SQLException {
st.setTimestamp( index, javaTypeDescriptor.unwrap( value, Timestamp.class, options ), Calendar.getInstance(UTC) );
}
};
}
public <X> ValueExtractor<X> getExtractor(final JavaTypeDescriptor<X> javaTypeDescriptor) {
return new BasicExtractor<X>( javaTypeDescriptor, this ) {
@Override
protected X doExtract(ResultSet rs, String name, WrapperOptions options) throws SQLException {
return javaTypeDescriptor.wrap( rs.getTimestamp( name, Calendar.getInstance(UTC) ), options );
}
};
}
}
接下来创建UtcTimestampType,该类型使用UtcTimestampTypeDescriptor作为超类构造函数调用中的SqlTypeDescriptor,但除此之外将所有内容委派给TimestampType:
然后创建UtcTimestampType,它在超类构造函数调用中使用UtcTimestampTypeDescriptor作为SqlTypeDescriptor,但是除此之外,它将所有内容委派给TimestampType。
public class UtcTimestampType
extends AbstractSingleColumnStandardBasicType<Date>
implements VersionType<Date>, LiteralType<Date> {
public static final UtcTimestampType INSTANCE = new UtcTimestampType();
public UtcTimestampType() {
super( UtcTimestampTypeDescriptor.INSTANCE, JdbcTimestampTypeDescriptor.INSTANCE );
}
public String getName() {
return TimestampType.INSTANCE.getName();
}
@Override
public String[] getRegistrationKeys() {
return TimestampType.INSTANCE.getRegistrationKeys();
}
public Date next(Date current, SessionImplementor session) {
return TimestampType.INSTANCE.next(current, session);
}
public Date seed(SessionImplementor session) {
return TimestampType.INSTANCE.seed(session);
}
public Comparator<Date> getComparator() {
return TimestampType.INSTANCE.getComparator();
}
public String objectToSQLString(Date value, Dialect dialect) throws Exception {
return TimestampType.INSTANCE.objectToSQLString(value, dialect);
}
public Date fromStringValue(String xml) throws HibernateException {
return TimestampType.INSTANCE.fromStringValue(xml);
}
}
最后,在初始化Hibernate配置时,请将UtcTimestampType注册为类型覆盖:
configuration.registerTypeOverride(new UtcTimestampType());
现在,时间戳在传输到和从数据库返回时不应与JVM的时区相关。希望这对你有帮助。