mybatis 根據id批量刪除的實現操作
第一種,直接傳遞給mapper.xml 集合/數組形式
<delete 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 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 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批量刪除的實現操作就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持好吧啦網。
相關文章: