一、前提背景
程序执行到查询数据库时报如下错误:
org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.exceptions.PersistenceException:
### Error querying database. Cause: java.lang.IllegalArgumentException: invalid comparison: java.util.Date and java.lang.String
### Cause: java.lang.IllegalArgumentException: invalid comparison: java.util.Date and java.lang.String
代码中的mapper文件,一个基本查询语句,我们这里只看下where子句的查询条件:
<sql id="queryHandNoListWhere">
<where>
<if test="startTime != null and startTime != '' and endTime != null and endTime != ''">
<if test="startTime != null and endTime != null ">
and shipM.CREATE_TIME between #{startTime,jdbcType=TIMESTAMP} and
#{endTime,jdbcType=TIMESTAMP}
</if>
<if test="outboundType != null and outboundType != '' ">
and shipD.outbound_type = #{outboundType,jdbcType=VARCHAR}
</if>
</where>
</sql>
查询条件的实体对象:
public class ObInternalShipHandNoQuery{
...
private Date startTime;
private Date endTime;
}
这样看上去好像没问题啊,Date类型对应数据库的TIMESTAMP时间戳类型。
二、解决办法
网上搜了好多,都说是Mybatis版本问题,Mybatis3.3.0以上版本不支持判断空字符串,否则会报该
PersistenceException异常。看了下自己项目中的是3.4.1版本,所以去掉判断条件中的判断空字符串
<sql id="queryHandNoListWhere">
<where>
<!--去掉原来的判断空字符串,否则mybatis3.3.0以上版本会报PersistenceException异常-->
<if test="startTime != null and endTime != null ">
and shipM.CREATE_TIME between #{startTime,jdbcType=TIMESTAMP} and
#{endTime,jdbcType=TIMESTAMP}
</if>
<if test="outboundType != null and outboundType != '' ">
and shipD.outbound_type = #{outboundType,jdbcType=VARCHAR}
</if>
</where>
</sql>
OK,问题解决了,关于具体逻辑,就需要我们去Mybatis源码中去寻找了,小编还在刚开始看源码,找到的时候再进行完善。