解決myBatis中刪除條件的拼接問(wèn)題
今天剛剛學(xué)習(xí)了mybatis,做了簡(jiǎn)單的對(duì)數(shù)據(jù)庫(kù)的增刪改查。在進(jìn)行刪除操作時(shí),單條刪除時(shí)很簡(jiǎn)單,但是批量刪除的時(shí)候拼接刪除條件卻有些麻煩,現(xiàn)記錄一下做法。
Sql語(yǔ)句中,當(dāng)刪除條件并不唯一的時(shí)候,我們有兩種刪除的sql語(yǔ)句,一種使用or拼接where中的條件,例如delete from 表名where 條件1 or 條件2,另一種是使用in 例如delete from 表名where 元素in( )
利用第一種刪除語(yǔ)句在mybatis中的mapping.xml中進(jìn)行拼接:
利用第二種刪除語(yǔ)句在mybatis中的mapping.xml中進(jìn)行拼接:
以上刪除操作基本完成,但是,這樣有一個(gè)缺陷,當(dāng)查詢條件idList中沒(méi)有元素的時(shí)候,會(huì)刪除整個(gè)表ac01中的記錄。所以,我們需要對(duì)上述方法進(jìn)行改進(jìn)。
第二種刪除語(yǔ)句進(jìn)行改進(jìn)后:
第一種刪除語(yǔ)句進(jìn)行改進(jìn)后:
至此,刪除操作完美完成。
補(bǔ)充知識(shí):myBatis 查詢時(shí)注意and拼接條件
<!-- 加個(gè)條件 -->
<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>
例如上訴問(wèn)題 要么都加and ,要么都不加 ,一定要注意,如果有加and 和沒(méi)有加and的 查詢會(huì)報(bào)錯(cuò)
以上這篇解決myBatis中刪除條件的拼接問(wèn)題就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. 解決Mybatis中mapper.xml文件update,delete及insert返回值問(wèn)題2. MySQL 鎖的相關(guān)知識(shí)總結(jié)3. mysql之如何查找配置文件my.ini的位置4. mysql啟動(dòng)時(shí)報(bào)錯(cuò) ERROR! Manager of pid-file quit without5. MySQL系列之二 多實(shí)例配置6. 詳解MySQL批量入庫(kù)的幾種方式7. DB2數(shù)據(jù)庫(kù)使用經(jīng)驗(yàn)漫談(1)8. mysql 數(shù)據(jù)庫(kù)優(yōu)化技巧9. MySql關(guān)于null的函數(shù)使用分享10. 拋磚引玉,實(shí)例講解DB2中的表空間(1)
