mybatis 根据id批量删除的两种方法

原文链接

直接传递给mapper.xml 集合/数组形式
  1. 如果传入的是单参数且参数类型是一个List的时候,collection属性值为list
1
int (List list);
1
2
3
4
5
6
<delete id="deleteByLogic"  parameterType = "java.util.List">
delete from user where id in
<foreach collection="list" item="item" open="(" separator="," close=")" >
     #{item}
</foreach>
</delete>
  1. 如果传入的是单参数且参数类型是一个array数组的时候,集合collection的属性值为array
1
int (int[] array);
1
2
3
4
5
6
<delete id="deleteByLogic"  parameterType = "int">
delete from user where id in
<foreach item="item" collection="array" open="(" separator="," close=")">
#{item}
</foreach>
</delete>

直接在service中将数据给分装传递到mapper中
前端封装为以“ , ”为分隔符的id字符串。调用下方工具类。生成数据类型为(‘12’, ‘34’….)形式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30

* StringUtil.getSqlInStrByStrArray()<BR>
* <P>Author : wyp </P>
* <P>Date : 2016年6月15日下午6:14:05</P>
* <P>Desc : 数组字符串转换为SQL in 字符串拼接 </P>
* @param strArray 数组字符串
* @return SQL in 字符串
*/
public static String getSqlInStrByStrArray(String str) {
StringBuffer temp = new StringBuffer();
if(StringUtils.isEmpty(str)){
return "('')";
}
temp.append("(");
if(StringUtils.isNotEmpty(str)){
String[] strArray=str.split(",");
if (strArray != null && strArray.length > 0 ) {
for (int i = 0; i < strArray.length; i++) {
temp.append("'");
temp.append(strArray[i]);
temp.append("'");
if (i != (strArray.length-1) ) {
temp.append(",");
}
}
}
}
temp.append(")");
return temp.toString();
}

在mapper中直接使用 $ 符号接收即可

1
int deleteByLogic(String ids);
1
2
3
<delete id="deleteByLogic"  parameterType = "java.util.List">
delete from user where id in ${ids}
</delete>
直接在service中循环调用mapper中的delete方法
1
int (int id);
1
2
3
<delete id="deleteByLogic"  parameterType = "int">
delete from user where id = #{id}
</delete>