解決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è)參考,也希望大家多多支持本站。
版權(quán)聲明:本站文章來(lái)源標(biāo)注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請(qǐng)保持原文完整并注明來(lái)源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非maisonbaluchon.cn所屬的服務(wù)器上建立鏡像,否則將依法追究法律責(zé)任。本站部分內(nèi)容來(lái)源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來(lái),僅供學(xué)習(xí)參考,不代表本站立場(chǎng),如有內(nèi)容涉嫌侵權(quán),請(qǐng)聯(lián)系alex-e#qq.com處理。
關(guān)注官方微信