AdSense

網頁

2017/12/5

MyBatis java.lang.IllegalArgumentException: invalid comparison: java.util.Date and java.lang.String 錯誤

今天在用MyBatis查詢根據輸入Date的條件查詢時,發生下面錯誤。

### 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
 at org.mybatis.spring.MyBatisExceptionTranslator.translateExceptionIfPossible(MyBatisExceptionTranslator.java:79)
 at org.mybatis.spring.SqlSessionTemplate$SqlSessionInterceptor.invoke(SqlSessionTemplate.java:447)
 at com.sun.proxy.$Proxy12.selectList(Unknown Source)
 at org.mybatis.spring.SqlSessionTemplate.selectList(SqlSessionTemplate.java:231)
 at org.apache.ibatis.binding.MapperMethod.executeForMany(MapperMethod.java:137)
 at org.apache.ibatis.binding.MapperMethod.execute(MapperMethod.java:75)
 at org.apache.ibatis.binding.MapperProxy.invoke(MapperProxy.java:59)
        ...

問題發生的原因是還蠻愚蠢的,但有時候小小的錯誤也是找老半天,下面是造成錯誤的mapper範例,相信聰明的你應該是很快就發現問題了。

<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="idv.matt.mapper.UserProfileMapper">
  <resultMap id="UserProfileResultMap" type="idv.matt.model.UserProfile">
    <result column="USER_NAME" jdbcType="VARCHAR" property="userName" />
    <result column="PASSWORD" jdbcType="VARCHAR" property="password" />
    <result column="BIRTHDAY" jdbcType="DATE" property="birthday" />
  </resultMap>

  <select id="selectUser" resultMap="UserProfileResultMap" parameterType="idv.matt.model.UserProfile">
    SELECT USER_NAME, USER_EMAIL FROM USER_PROFILE
    <where>
      <if test="birthday != null and birthday != ''">
        AND BIRTHDAY > #{birthday,jdbcType=DATE}
      </if>
    </where>
  </select>
</mapper>

造成錯誤的原因是下面這一段,UserProfile.birthday的型態是Date,但在MyBatis的動態條件中卻有是否為空字串的判斷而造成錯誤,所以只要把birthday != ''拿掉就好了。

<if test="birthday != null and birthday != ''">

沒有留言:

AdSense