Hibernate 的TemporalType.TIMESTAMP
映射到java.sql.Timestamp
. 构造Timestamp
函数采用 Long 值,即自纪元以来的毫秒数。数据库中的值存储为 Unix 时间戳,即自纪元以来的秒数。
我写了一个UnixTimestampType
需要几秒钟而不是几毫秒并创建Date
实例的代码:
public class UnixTimestampType extends AbstractSingleColumnStandardBasicType<Date> implements IdentifierType<Date>, LiteralType<Date> {
private static final long serialVersionUID = 1L;
public static final UnixTimestampType INSTANCE = new UnixTimestampType();
public UnixTimestampType() {
super(UnixTimestampTypeDescriptor.INSTANCE, JdbcDateTypeDescriptor.INSTANCE);
}
@Override
public String getName() {
return "date";
}
@Override
public String[] getRegistrationKeys() {
return new String[] { getName(), java.sql.Date.class.getName() };
}
@Override
public String objectToSQLString(Date value, Dialect dialect) throws Exception {
final java.sql.Date jdbcDate = java.sql.Date.class.isInstance(value) ? (java.sql.Date) value : new java.sql.Date(value.getTime());
return StringType.INSTANCE.objectToSQLString(jdbcDate.toString(), dialect);
}
@Override
public Date stringToObject(String xml) {
return fromString(xml);
}
}
和
public class UnixTimestampTypeDescriptor implements SqlTypeDescriptor {
private static final long serialVersionUID = 1L;
public static final UnixTimestampTypeDescriptor INSTANCE = new UnixTimestampTypeDescriptor();
@Override
public int getSqlType() {
return Types.INTEGER;
}
@Override
public boolean canBeRemapped() {
return true;
}
@Override
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 {
Date date = javaTypeDescriptor.unwrap(value, Date.class, options);
date.setTime(date.getTime() / 1000);
st.setDate(index, date);
}
};
}
@Override
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 {
Date date = new Date(rs.getLong(name) * 1000);
return javaTypeDescriptor.wrap(date, options);
}
};
}
}