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中的值与接口中的参数不相符合

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值