Hibernate——配置文件中数据类型date与timestamp区别

来源:互联网 发布:开源房产cms 编辑:程序博客网 时间:2024/06/05 09:06

例如:

<property name="createDate" type="timestamp" column="createDate"/><property name="createDate" type="date" column="createDate"/>

  那么,使用了 date类型,不能保存时分秒,就使用了timestamp就能保存时分秒了。

  hibernate在保存和更新Date类型的数据到数据库的时候,如果设置不当,会舍弃时分秒,和数据库中Date类型的精确度不符(如Oracle的Date是带时分秒的).

  引起的原因主要是mapping文件中的字段类型被设成了type=”date”,而mapping文件一般都是通过hibernate提供的工具生成的,hibernate提供的工具默认把数据库端date型的字段设成type=”date”.从而Hibernate在用JDBC做数据库更新的时候会用 statement的setDate(index, sqlDate),插入数据库的日期只有年月日.

  下面的JDBC代码演示了这个问题:

String sql = "UPDATE Timetest T SET T.datev=? WHERE T.id=?";stmt = conn.prepareStatement(sql); // Java.sql.Date sqlDate = new java.sql.Date(26,7,2010); // sqlDate.setTime(System.currentTimeMillis()); // stmt.setDate(1, sqlDate); //如果是用setdate的方式,时分秒会被舍弃 //用setTimestamp的方式,时分秒会被保存 stmt.setTimestamp(1, new Timestamp(System.currentTimeMillis())); stmt.setLong(2, 1L); stmt.executeUpdate(); conn.commit();
  • 使用时需要注意的问题:

    1,如果是用Hibernate的对象来影射数据库操作(save,load..),需要将mapping文件的type=”date”改成type=”timestamp”.

    2,如果用Query(session的createQuerycreateSQLQuery),在赋值的时候用query.setTimestamp(0, new Date());

原创粉丝点击