MyBatis案例九:动态sql(foreach)
说明:
foreach 元素的功能非常强大,它允许你指定一个集合,声明可以在元素体内使用的集合项(item)和索引(index)变量。它也允许你指定开头与结尾的字符串以及在迭代结果之间放置分隔符。这个元素是很智能的,因此它不会偶然地附加多余的分隔符。
注意 你可以将任何可迭代对象(如 List、Set 等)、Map 对象或者数组对象传递给 foreach 作为集合参数。当使用可迭代对象或者数组时,index 是当前迭代的次数,item 的值是本次迭代获取的元素。当使用 Map 对象(或者 Map.Entry 对象的集合)时,index 是键,item 是值。
- 接口方法:
public int batchDelete(List<Integer> list);
- mapper:
<delete id="batchDelete">
delete from dept where deptno in
<foreach collection="list" item="deptno" open="(" close=")" separator=",">
#{deptno}
</foreach>
</delete>
- 测试代码中:
@Test
public void testBatchDelete() throws IOException {
List<Integer> list = new ArrayList<>();
list.add(12);
list.add(13);
int n = mapper.batchDelete(list);
session.commit();// 提交事务
System.out.println(n);
}
- 改进:数组
public int batchDelete(int[] deptnos);
<delete id="batchDelete">
delete from dept where deptno in
<foreach collection="array" item="deptno" open="(" close=")" separator=",">
#{deptno}
</foreach>
</delete>
@Test
public void testBatchDelete() throws IOException {
int n = mapper.batchDelete(new int[] {12,13});
session.commit();// 提交事务
System.out.println(n);
}