[英]How do I map a hibernate Timestamp to a MySQL BIGINT?
我正在使用Hibernate 3.x,MySQL 4.1.20和Java 1.6。 我正在将Hibernate Timestamp映射到MySQL TIMESTAMP。 到现在为止还挺好。 问题是MySQL以秒为单位存储TIMESTAMP并丢弃毫秒,现在我需要毫秒精度。 我想我可以在我的表中使用BIGINT而不是TIMESTAMP并转换我的Java代码中的类型。 我试图弄清楚是否有更好的方法使用hibernate,mysql,JDBC或其他组合这样做,所以我仍然可以在我的HSQL和/或SQL查询中使用日期函数?
另外,请看创建自定义Hibernate Type实现。 有点像(psuedocode,因为我没有方便的环境,使其防弹):
public class CalendarBigIntType extends org.hibernate.type.CalendarType {
public Object get(ResultSet rs, String name) {
return cal = new GregorianCalendar(rs.getLong(name));
}
public void set(PreparedStatement stmt, Object value, int index) {
stmt.setParameter(index, ((Calendar) value).getTime());
}
}
然后,您需要使用hibernate TypeDef和Type映射来映射新对象。 如果您正在使用Hibernate注释,它将遵循以下方式:
@TypeDef (name="bigIntCalendar", typeClass=CalendarBigIntType.class)
@Entity
public class MyEntity {
@Type(type="bigIntCalendar")
private Calendar myDate;
}
对于那些仍然对此问题感兴趣的人:MySQL 5.6.4支持精确的时间戳。 对MySQL5Dialect进行子类化以覆盖使用的MySQL类型解决了这个问题。
我将我的数据类型从时间戳改为十进制(17,3)并编写了一些辅助方法
public static Calendar bigDec2Cal(BigDecimal tsp) {
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(tsp.longValue());
return cal;
}
public static Date bigDec2Date(BigDecimal tsp) {
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(tsp.longValue());
return cal.getTime();
}
public static BigDecimal cal2BigDec(Calendar cal) {
BigDecimal tsp = new BigDecimal(cal.getTimeInMillis());
return tsp;
}
public static BigDecimal date2BigDec(Date date) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
BigDecimal tsp = new BigDecimal(cal.getTimeInMillis());
return tsp;
}
除TIMESTAMP字段外,为什么不使用它? 您将有一个字段(已定义)用于存储日期(没有毫秒),另一个字段用于毫秒。 您仍然可以在第一个字段上运行HSQL查询,除非您必须确保正确地存储毫秒(通过在使用Hibernate存储之前解析Java Date对象)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.