POJO
private Timestamp dateCreated;
Mysql的建表语句中
date_created timestamp);
Hibernate映射文件中
<property name="dateCreated" type="java.sql.Timestamp">
<column name="date_created" length="19" />
</property>
代码中
user.setDateCreated(new Timestamp(System.currentTimeMillis()));
POJO保存进数据库时,出现异常:
org.hibernate.exception.DataException: Incorrect datetime value: '' for column 'date_created' at row 1
at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:134)
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:49)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:125)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:110)
Caused by: java.sql.SQLException: Incorrect datetime value: '' for column 'date_created' at row 1
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:2921)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1570)
at com.mysql.jdbc.ServerPreparedStatement.serverExecute(ServerPreparedStatement.java:1085)
at com.mysql.jdbc.ServerPreparedStatement.executeInternal(ServerPreparedStatement.java:670)
通过找资料,发现这是Mysql的bug。
原文:http://bugs.mysql.com/bug.php?id=65418
How to repeat: - Create a timestamp in java (only?), new Timestamp(System.currentTimeMillis()) - Run the code on a win7, 64-bit machine. - Connect to a 32-bit win7 MySQL instance. - Insert the timestamp value into a column of type timestamp.
以上四条在自己的机器上均符合。
OS: Microsoft Windows 7 Ultimate Edition Service Pack 1 (build 7601), 64-bit
CPU: 4x Intel(R) Core(TM) i5-3230M CPU @ 2.60GHz, 7.9 GiB RAM
MySQL 5.2.47 SE Revision 10398
暂未找到解决办法。
保持时间戳为空时,插入数据库会是当前时间。
另:
参考:http://stackoverflow.com/questions/782823/handling-datetime-values-0000-00-00-000000-in-jdbc
这个方法无法使保存在数据库的时间戳为0。