前言:
在使用mybatis的時候,有的mapper接口需要傳入多個類型參數的接口,這時候一不小心就會出現題目中所提到的問題,這篇文章就這種情況出現的bug講解下bug出現的原因以及解決方案。
正文:
一、復現問題
首先看下我的各層代碼:
1.post請求界面
2.controller層代碼
3.service層代碼
4.serviceimpl層代碼
5.dao層代碼
6.mapper.xml層代碼
錯誤信息:
nested exception is org.apache.ibatis.type.TypeException: Could not set parameters for mapping: ParameterMapping{property='age', mode=IN, javaType=class java.lang.String, jdbcType=null, numericScale=null, resultMapId='null', jdbcTypeName='null', expression='null'}. Cause: org.apache.ibatis.type.TypeException: Error setting non null for parameter #2 with JdbcType null . Try setting a different JdbcType for this parameter or a different configuration property. Cause: java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String
二、分析問題
我從錯誤信息可以很明顯讀到類型轉換異常的錯誤,由於又是ibatis報的,那肯定是dao層到 mapper.xml參數注入的時候轉換異常啦,可以仔細看下我的參數
List<Student> selectByName(@Param("name") String name, @Param("age") int age,@Param("id")Long id);
有三種數據類型,而我的mapper.xml裏參數類型只寫了一種 parameterType="java.lang.String",所以參數注入的時候肯定轉換異常。
<select id="selectByName" resultMap="BaseResultMap" parameterType="java.lang.String">
select * from student where name =#{name} and age =#{age} and id=#{id}
</select>
三、解決問題
想解決這個問題,只需要把parameterType去掉即可
<select id="selectByName" resultMap="BaseResultMap">
select * from student where name =#{name} and age =#{age} and id=#{id}
</select>
或者用map和對象進行傳參,也可以間接解決,mybatis多參數傳參可以見下一篇博客。
總結:
今日份雞湯,如果不能成爲一個有錢的人,那就努力成爲一個自己喜歡的人。
我是阿達,一名喜歡分享知識的程序員,時不時的也會荒腔走板的聊一聊電影、電視劇、音樂、漫畫,這裏已經有7600位小夥伴在等你們啦,感興趣的就趕緊來點擊關注我把,哪裏有不明白或有不同觀點的地方歡迎留言!