Data truncation: Incorrect datetime value
在使用Hibernate插入数据时,报错:Data truncation: Incorrect datetime value: ‘’ for column ‘ENDTIME’ at row 1,出现过两次了,记录一下:
问题
问题代码大概如下,将某个时间的毫秒数加上一个数值后做为参数传递给Timestamp创建时间戳对象,之后调用Hibernate的save方法保存:
long dateTime = param.getDateTime();
long duration = TestUtil.getRandomDuration();
entity.setEndTime(new Timestamp(dateTime + duration));
getHibernateTemplate().save(entity);
运行之后报错:
Caused by: java.sql.BatchUpdateException: Data truncation: Incorrect datetime value: '' for column 'ENDTIME' at row 1
at com.mysql.jdbc.ServerPreparedStatement.executeBatch(ServerPreparedStatement.java:656)
at org.apache.commons.dbcp.DelegatingStatement.executeBatch(DelegatingStatement.java:294)
at org.hibernate.jdbc.BatchingBatcher.doExecuteBatch(BatchingBatcher.java:70)
at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:268)
... 44 more
处理方式
先将日期格式化为字符串,再使用Timestamp.valueOf()
方法创建时间戳对象:
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
entity.setEndTime(Timestamp.valueOf(format.format(new Date(time + duration))));