org.apache.ibatis.binding.BindingException: Parameter 'idList' not found解决办法

问题描述

使用Mybatis查询数据库报错:

org.apache.ibatis.binding.BindingException: Parameter 'idList' not found

接口是这样的:

public List<User> findByIdList(List<Integer> idList);

XML是这样的:

<select id="findByIdList" resultType="com.example.bean.User">
	SELECT id, name, password, address, enable
	FROM user
	<where>
        <if test="idList != null and idList.size() > 0">
            id IN
            <foreach collection="idList" item="ietm" index="index" open="(" separator="," close=")">
                #{item}
            </foreach>
        </if>
	</where>
</select>

运行报错:org.apache.ibatis.binding.BindingException: Parameter 'idList' not found.

原因分析

Mybatis传递参数是按位置传递的,也就是说下面一个接口:public User find(String name, String password), XML中使用参数是这样的select * from user where name = #{0} and password = #{1}.
如果想要按值传递,就得这样写:

// 接口
public User find(@Param("name")String name, @Param("password")String password)

<!-- xml -->
select * from user where name = #{name} and password = #{password}

这样一看是不是明白了?Mybatis是按顺序传递参数的。
想要在xml中通过参数的name获取,就得加上@Param("")注解,不然就只能使用Mybatis默认的写法。

解决办法

解决办法有两种:

Mybatis默认写法——list

第一种写法是使用Myabtis默认的写法, 在xml中用list接收参数,如下:

// 接口
public List<User> findByIdList(List<Integer> idList);

<select id="findByIdList" resultType="com.example.bean.User">
	SELECT id, name, password, address, enable
	FROM user
	<where>
        <if test="list!= null and list.size() > 0">
            id IN
            <foreach collection="list" item="ietm" index="index" open="(" separator="," close=")">
                #{item}
            </foreach>
        </if>
	</where>
</select>

使用注解

第二种方式就是使用@Param("")注解,如下:

// 接口
public List<User> findByIdList(@Param("idList")List<Integer> idList);

<select id="findByIdList" resultType="com.example.bean.User">
	SELECT id, name, password, address, enable
	FROM user
	<where>
        <if test="idList!= null and idList.size() > 0">
            id IN
            <foreach collection="idList" item="ietm" index="index" open="(" separator="," close=")">
                #{item}
            </foreach>
        </if>
	</where>
</select>

Mybatis默认参数传递方式

Mybatis关于各种类型的单参数默认的写法如下:

类型接收参数方式
基本数据类型顺序,如#{0},也可以用name直接获取,如#{name}
Listlist
数组array
Map根据key获取map中各参数即可,如#{key}
自定义的对象根据get方法对应的参数,使用name获取即可,如#{name}

如果是多参数,比如public User find(String address, List<Integer> idList), 使用注解@Param("")或者考虑封装在map中传递。

评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值