如何将休眠时间戳映射到MySQL BIGINT?

时间:2008-12-15 19:34:42

标签: java mysql hibernate orm jdbc

我正在使用Hibernate 3.x,MySQL 4.1.20和Java 1.6。我正在将Hibernate Timestamp映射到MySQL TIMESTAMP。到现在为止还挺好。问题是MySQL以秒为单位存储TIMESTAMP并丢弃毫秒,现在我需要毫秒精度。我想我可以在我的表中使用BIGINT而不是TIMESTAMP并转换我的Java代码中的类型。我试图弄清楚是否有更好的方法使用hibernate,mysql,JDBC或其他组合,所以我仍然可以在我的HSQL和/或SQL查询中使用日期函数?

4 个答案:

答案 0 :(得分:3)

另外,请看创建自定义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;
}

答案 1 :(得分:1)

对于仍然对此问题感兴趣的人:MySQL 5.6.4支持精确的时间戳。对MySQL5Dialect进行子类化以覆盖使用的MySQL类型可以解决问题。

答案 2 :(得分:0)

为什么不在TIMESTAMP字段之外使用它?您将有一个字段(已定义)用于存储日期(没有毫秒),另一个字段用于毫秒。您仍然可以在第一个字段上运行HSQL查询,除非您必须确保正确地存储毫秒(通过在使用Hibernate存储之前解析Java Date对象)。

答案 3 :(得分:0)

我将我的数据类型从时间戳改为十进制(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;
}