mybatis DateTypeHandler无法将java Date转换为sql TIMESTAMP

时间:2017-07-20 09:26:42

标签: java mysql mybatis spring-mybatis

我希望在MySQL中存储Date作为TIMESTAMP。我发现DateTypeHandler似乎可以进行此转换。我把它放在我的项目中,但它失败了。

我在“mapper.xml”中尝试了以下两种情况,但都失败了。

<insert id="insertUser">
    insert into user (user_id, password, token,
    register_time, user_type, account_type) values (
    #{userId},
    #{password}, #{token}, #{registerTime, jdbcType=TIMESTAMP,
    javaType=java.util.Date, typeHandler=org.apache.ibatis.type.DateTypeHandler},
    #{userType},
    #{accountType}
    )
</insert>

<insert id="insertUser">
    insert into user (user_id, password, token,
    register_time, user_type, account_type) values (
    #{userId},
    #{password}, #{token}, #{registerTime, typeHandler=org.apache.ibatis.type.DateTypeHandler},
    #{userType},
    #{accountType}
    )
</insert>

错误日志如下:

org.springframework.dao.DataIntegrityViolationException: 
### Error updating database.  Cause: com.mysql.jdbc.MysqlDataTruncation: 
Data truncation: Incorrect datetime value: '3892-04-19 00:00:00' for column 
'register_time' at row 1
### The error may involve defaultParameterMap
### The error occurred while setting parameters
### SQL: insert into user (user_id, password, token,   register_time, user_type, account_type) values (   ?,   ?, ?, ?,   ?,   ?   )
### Cause: com.mysql.jdbc.MysqlDataTruncation: Data truncation: Incorrect 
datetime value: '3892-04-19 00:00:00' for column 'register_time' at row 1
; SQL []; Data truncation: Incorrect datetime value: '3892-04-19 00:00:00' 
for column 'register_time' at row 1; nested exception is com.mysql.jdbc.MysqlDataTruncation: Data truncation: org.springframework.dao.DataIntegrityViolationException: 

1 个答案:

答案 0 :(得分:0)

MySql TIMESTAMP类型只能存储&#39; 1970-01-01 00:00:01&#39;范围内的数据值。 UTC到&#39; 2038-01-19 03:14:07&#39; UTC,您尝试插入值&#39; 3892-04-19 00:00:00&#39;在register_time列中,这是这种类型。这会引发错误:

Data truncation: Incorrect datetime value: '3892-04-19 00:00:00' for column register_time' at row 1

检查此未来日期是否正确,如果是,请将mapper.xml中的jdbcType=TIMESTAMP,更改为jdbcType=DATETIME以解决此问题。 (MySql DATETIME类型支持的范围是&#39; 1000-01-01 00:00:00&#39;到&#39; 9999-12-31 23:59:59&#39;。

参考文献:MySql doc