原文:https://blog.csdn.net/qq_40010745/article/details/81032218
mybatis 根據id批量刪除的兩種方法
第一種,直接傳遞給mapper.xml 集合/數組形式
-
< delete id="deleteByLogic" parameterType = "java.util.List">
-
delete from user where 1>2
-
or id in
-
< foreach collection="list" item="item" open="(" separator="," close=")" >
-
#{item}
-
< /foreach>
-
</delete>
1. 如果傳入的是單參數且參數類型是一個List的時候,collection屬性值為list
int deleteByLogic(List list);
2. 如果傳入的是單參數且參數類型是一個array數組的時候, 參數類型為parameterType="int" 集合 collection的屬性值為array
int deleteByLogic(int[] array);
-
<foreach item="item" collection="array" open="(" separator="," close=")">
-
#{item}
-
</foreach>
第二種,直接在service中將數據給分裝傳遞到mapper中
前端封裝為以,為分隔符的id字符串。調用下方工具類。生成數據類型為(‘12’,‘34’....)形式
-
/**
-
* 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中直接使用 $ 符號接收即可
int deleteByLogic(String ids);
-
<delete id="deleteByLogic" parameterType = "java.util.List">
-
delete from user where 1>2
-
or id in ${ids}
-
</delete>
還有第三種。不過比較浪費資源
直接在service中循環調用mapper中的delete方法。.....