一、原因 使用Mybatis查询一条数据时 返回 异常如下:
org.springframework.dao.TransientDataAccessResourceException: Error attempting to get column 'update_time' from result set. Cause: java.sql.SQLException: Zero date value prohibited
然后去查了一下 是因为 数据库里存的update_time 的格式是 : 0000-00-00 00:00:00 ,所以在set到实体类是转换Date 报错了!
二、解决方法
1. 把数据库里的update_time 时间改成一个准确的时间就可以了!然后确保 每次插入数据 都 用数据库里的 now() ,或者 数据库里设置默认值 为null 等等多种方法,使他不要是 无效的时间格式就ok。
2. 数据库配置增加zeroDateTimeBehavior 属性
jdbc:mysql://yourserver:3306/yourdatabase?zeroDateTimeBehavior=convertToNull
根据查阅的 官方给出的 异常提示
zeroDateTimeBehavior What should happen when the driver encounters
DATETIME values that are composed entirely of zeros (used by MySQL to
represent invalid dates)? Valid values are “exception”, “round” and
“convertToNull”. Default: exception Since version: 3.1.4
http://dev.mysql.com/doc/connector-j/5.1/en/connector-j-installing-upgrading-3-0-to-3-1.html
大致的意思:zeroDateTimeBehavior 属性,当遇到DATETIME值完全由0组成时,最终的有效值可以设置为,异常(exception),一个近似值(round),或将这个值转换为null(convertToNull)。
也就是说
1. zeroDateTimeBehavior 设置为 exception(不设置时是默认),(设置这个属性会抛出一个SQLException异常,其SQLSate码为S1009)
2. zeroDateTimeBehavior 设置为 convertToNull ,数据库会返回 null来代替 0000-00-00 这样的无效日期
3. zeroDateTimeBehavior 设置为 round,数据库 会将日期转换为0001-01-01 返回。