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}
List list
数组 array
Map 根据key获取map中各参数即可,如#{key}
自定义的对象 根据get方法对应的参数,使用name获取即可,如#{name}

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

你可能感兴趣的:(mybatis,mybatis)