1. 程式人生 > >org.apache.ibatis.binding.BindingException: Parameter 'idList' not found解決辦法

org.apache.ibatis.binding.BindingException: Parameter 'idList' not found解決辦法

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<Integer> idList), 使用註解@Param("")或者考慮封裝在map中傳遞。