MyBatie使用List資料型別進行批量刪除
阿新 • • 發佈:2018-12-16
進行一項批量刪除的功能,使用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一下,打完收工。