當我們配置需要參數的sql語句時,有時候會遇見參數無法獲取的原因
### Error updating database. Cause: org.apache.ibatis.binding.BindingException: Parameter 'roleName' not found. Available parameters are [0, 1, 2, param3, param1, param2]
### Cause: org.apache.ibatis.binding.BindingException: Parameter 'roleName' not found. Available parameters are [0, 1, 2, param3, param1, param2]
原因如下:
public int updateRole(String roleName,String note,Long id);
我在接口中定義了三個參數
<update id="updateRole" parameterType="role" >
update role
<set>
<if test="roleName !=null and roleName!=''">
roleName=#{roleName},
</if>
<if test="note!=null and note!=''">
note=#{role.note}
</if>
</set>
where id=#{role.id}
</update>
但是xml中parameterType設置爲實體類的名字role,這就會造成無法找到參數的問題
**解決方法:**
1;啓用註解的方式,
public int updateRole(@Param("roleName")String roleName,@Param("note")String note,@Param("id")Long id);
<update id="updateRole">
這裏的parameterType就不需要了
將查詢中需要的參數,在接口中全部加上註解,注意@Param中的名字要與查詢中的參數名字相同,否則會報錯
2 解決方法2
參數變爲map類型
接口的參數變爲map
public void updateRole(Map<String, String> params);
parameterType變爲map
<update id="updateRole" parameterType="map">
update role
<set>
<if test="roleName !=null and roleName!=''">
roleName=#{roleName},
</if>
<if test="note!=null and note!=''">
note=#{note}
</if>
</set>
where id=#{id}
</update>
測試類中傳入map參數
Map<String, String> params=new HashMap<String, String>();
params.put("roleName", "555555");
params.put("note", "555555");
params.put("id", "1L");
roleMapper.updateRole(params);
sqlSession.commit();
這樣子就不會報錯了
設置map的時候,KV都爲String即可,不影響參數的類型
參數無法獲取的幾個問題點
1 parameterType 設置錯了,或者沒設置,或者加了註解不該設置卻設置了
2 parameterType中的值與接口中的參數不相符合