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

原文:https://blog.csdn.net/qq_40010745/article/details/81032218

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

第一种,直接传递给mapper.xml  集合/数组形式

  1. <delete id="deleteByLogic" parameterType = "java.util.List">
  2. delete from user where 1>2
  3.     or id in
  4. <foreach collection="list" item="item" open="(" separator="," close=")" >
  5.      #{item}
  6. </foreach>
  7. </delete>
 

1.     如果传入的是单参数且参数类型是一个List的时候,collection属性值为list

int deleteByLogic(List list);

2.     如果传入的是单参数且参数类型是一个array数组的时候, 参数类型为parameterType="int"     集合    collection的属性值为array 

int deleteByLogic(int[] array);
 
  1. <foreach item="item" collection="array" open="(" separator="," close=")">
  2. #{item}
  3. </foreach>

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

  1. /**
  2. * StringUtil.getSqlInStrByStrArray()<BR>
  3. * <P>Author : wyp </P>
  4. * <P>Date : 2016年6月15日下午6:14:05</P>
  5. * <P>Desc : 数组字符串转换为SQL in 字符串拼接 </P>
  6. * @param strArray 数组字符串
  7. * @return SQL in 字符串
  8. */
  9. public static String getSqlInStrByStrArray(String str) {
  10. StringBuffer temp = new StringBuffer();
  11. if(StringUtils.isEmpty(str)){
  12. return "('')";
  13. }
  14. temp.append("(");
  15. if(StringUtils.isNotEmpty(str)){
  16. String[] strArray=str.split(",");
  17. if (strArray != null && strArray.length > 0 ) {
  18. for (int i = 0; i < strArray.length; i++) {
  19. temp.append("'");
  20. temp.append(strArray[i]);
  21. temp.append("'");
  22. if (i != (strArray.length-1) ) {
  23. temp.append(",");
  24. }
  25. }
  26. }
  27. }
  28. temp.append(")");
  29. return temp.toString();
  30. }
  31.  

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

int deleteByLogic(String ids);
  1. <delete id="deleteByLogic" parameterType = "java.util.List">
  2. delete from user where 1>2
  3. or id in ${ids}
  4. </delete>

还有第三种。不过比较浪费资源

        直接在service中循环调用mapper中的delete方法。.....

原文地址:https://www.cnblogs.com/libin6505/p/10076518.html