解決myBatis中刪除條件的拼接問題
今天剛剛學(xué)習(xí)了mybatis,做了簡單的對數(shù)據(jù)庫的增刪改查。在進(jìn)行刪除操作時(shí),單條刪除時(shí)很簡單,但是批量刪除的時(shí)候拼接刪除條件卻有些麻煩,現(xiàn)記錄一下做法。
Sql語句中,當(dāng)刪除條件并不唯一的時(shí)候,我們有兩種刪除的sql語句,一種使用or拼接where中的條件,例如delete from 表名where 條件1 or 條件2,另一種是使用in 例如delete from 表名where 元素in( )
利用第一種刪除語句在mybatis中的mapping.xml中進(jìn)行拼接:

利用第二種刪除語句在mybatis中的mapping.xml中進(jìn)行拼接:

以上刪除操作基本完成,但是,這樣有一個缺陷,當(dāng)查詢條件idList中沒有元素的時(shí)候,會刪除整個表ac01中的記錄。所以,我們需要對上述方法進(jìn)行改進(jìn)。
第二種刪除語句進(jìn)行改進(jìn)后:

第一種刪除語句進(jìn)行改進(jìn)后:

至此,刪除操作完美完成。
補(bǔ)充知識:myBatis 查詢時(shí)注意and拼接條件
<!-- 加個條件 -->
<sql id='queryjiachaAllPageId'> <where> <if test='danweimc !=null and danweimc !=’’'> and jcb.danweimc like ’%${danweimc}%’ </if> <if test='ge_jianchaks !=null and ge_jianchaks !=’’'> and DATE_FORMAT(jcb.jianchaks, ’%Y-%m-%d’) >= #{ge_jianchaks} </if> <if test='le_jianchaks != null and le_jianchaks != ’’'> and DATE_FORMAT(jcb.jianchaks, ’%Y-%m-%d’) <= #{le_jianchaks} </if> <if test='jiancharxm !=null and jiancharxm !=’’'> and jcb.jiancharxm like ’%${jiancharxm}%’ </if> <if test='zhuangtai !=null and zhuangtai !=’’'> and yhb.zhuangtai = ${zhuangtai} </if> <if test='danweilb !=null and danweilb !=’’'> and yhb.yinhuanmc like ’${danweilb}%’ </if> <if test='jiedao != null and jiedao !=’’ and jiedao !=’110105000000’'> and jcb.jiedao=#{jiedao} </if> <if test='danweimcs != null and danweimcs !=’’'> and jcb.danweimc = #{danweimcs} </if> </where> </sql>
例如上訴問題 要么都加and ,要么都不加 ,一定要注意,如果有加and 和沒有加and的 查詢會報(bào)錯
以上這篇解決myBatis中刪除條件的拼接問題就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. Mysql入門系列:MYSQL創(chuàng)建、刪除、索引和更改表2. 導(dǎo)出錯誤編碼的mysql數(shù)據(jù)庫3. 整理Oracle數(shù)據(jù)庫碎片4. 數(shù)據(jù)庫相關(guān)的幾個技能:ACCESS轉(zhuǎn)SQL5. MySQL Community Server 5.1.496. MySQL中 concat函數(shù)的使用7. Delphi中的Access技巧集8. 快速刪除ORACLE重復(fù)記錄9. MYSQL數(shù)據(jù)庫存文本轉(zhuǎn)存數(shù)據(jù)庫問題10. 如何遠(yuǎn)程調(diào)用ACCESS數(shù)據(jù)庫

網(wǎng)公網(wǎng)安備