首页 > 编程技术 > java

mybatis 根据id批量删除的实现操作

发布时间:2020-8-27 08:33

第一种,直接传递给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方法。.....

补充知识:mybatis中一次执行多条SQL语句,例如一次性删除多条数据

1.首先在数据库连接URL上加上allowMultiQueries=true,默认mysql是不支持一次执行多条SQL语句的。

jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true

2.在delete节点中添加多条语句:

 <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >
   delete from music_favorite where id = #{id,jdbcType=INTEGER};
   delete from music_favorite_song where f_id = #{id,jdbcType=INTEGER};
 </delete>

这可以用在mybatis的级联关系删除上,删除主表记录前,先删除关联表的记录,两条一起执行。

以上这篇mybatis 根据id批量删除的实现操作就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持猪先飞。

标签:[!--infotagslink--]

您可能感兴趣的文章: