MyBatie使用List数据类型进行批量删除

进行一项批量删除的功能,使用MyBatis进行,数据类型为List,下面上代码:

	<!-- public int deleteList(List<Integer> addedIds); -->
	<delete id="deleteList" parameterType="java.util.List">
		DELETE FROM t_g_vaddedtax WHERE addedId in(
		<foreach collection="addedIds" item="id" index="index" separator=",">
			${id}
		</foreach>
		);
	</delete>

执行报错,错误信息如下:

18:05:31 [http-nio-80-exec-21] ERROR c.c.a.c.exception.BDExceptionHandler - nested exception is org.apache.ibatis.binding.BindingException: Parameter 'addedIds' not found. Available parameters are [collection, list]
org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.binding.BindingException: Parameter 'addedIds' not found. Available parameters are [collection, list]
	at org.mybatis.spring.MyBatisExceptionTranslator.translateExceptionIfPossible(MyBatisExceptionTranslator.java:79)

观察打印的错误日志信息,修改MyBatis代码:

	<!-- public int deleteList(List<Integer> list); -->
	<delete id="deleteList" parameterType="java.util.List">
		DELETE FROM t_g_vaddedtax WHERE addedId in(
		<foreach collection="list" item="id" index="index" separator=",">
			${id}
		</foreach>
		);
	</delete>

执行成功,注意,collections里边为小写的list,至于大写的List?你猜会不会抛出异常。

查了一下MyBatis的说明文档,里边对于foreach语句的介绍如下:

foreach
Another common necessity for dynamic SQL is the need to iterate over a collection, often to build an IN condition. For example:

<select id="selectPostIn" resultType="domain.blog.Post">
  SELECT *
  FROM POST P
  WHERE ID in
  <foreach item="item" index="index" collection="list"
      open="(" separator="," close=")">
        #{item}
  </foreach>
</select>
The foreach element is very powerful, and allows you to specify a collection, declare item and index variables that can be used inside the body of the element. It also allows you to specify opening and closing strings, and add a separator to place in between iterations. The element is smart in that it won’t accidentally append extra separators.

NOTE You can pass any Iterable object (for example List, Set, etc.), as well as any Map or Array object to foreach as collection parameter. When using an Iterable or Array, index will be the number of current iteration and value item will be the element retrieved in this iteration. When using a Map (or Collection of Map.Entry objects), index will be the key object and item will be the value object.

This wraps up the discussion regarding the XML configuration file and XML mapping files. The next section will discuss the Java API in detail, so that you can get the most out of the mappings that you’ve created.

上面的问题文档里边并没有提到,这里Mark一下,打完收工。

猜你喜欢

转载自blog.csdn.net/txd2016_5_11/article/details/83215504