Mybatis 参数无法获取Parameter not found

当我们配置需要参数的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中的值与接口中的参数不相符合

发布了28 篇原创文章 · 获赞 17 · 访问量 6万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章