mybatis中的if-else及if嵌套使用方式
if-else及if嵌套使用方式
案例一:if-else
在使用mybatis mapper 動(dòng)態(tài)sql時(shí),不免會(huì)出現(xiàn)if-else的使用,但是好像又沒(méi)有這種語(yǔ)法,提供的是choose標(biāo)簽代替if-else
例如:
select * from t_stu t <where> ? ? <choose> ? ? ? ? <when test="query == 0"> ? ? ? ? ? ? and t.status = 1? ? ? ? ? </when> ? ? ? ? <otherwise> ? ? ? ? ? ? ? ? and t.status ?NOT IN (9,5) ? ? ? ? </otherwise> ? ? </choose> ? ? and t.delete_status = 1 </where>
也可以用多個(gè)if判斷實(shí)現(xiàn):
select * from t_stu t <where> ? ? <if test="query == 0"> ? ? ? ? and t.status = 1? ? ? </if> ? ? <if test="query != 0"> ? ? ? ? and t.status ?NOT IN (9,5) ? ? </if> ? ? and t.delete_status = 1 </where>
案例二:if嵌套
在實(shí)際編碼過(guò)程中會(huì)有一些判斷條件會(huì)一直重復(fù)使用,一直寫(xiě)在if標(biāo)簽中寫(xiě)的代碼會(huì)特長(zhǎng),而且臃腫
select * from t_stu t <where> ? ? <if test="query == 0 and type = 1"> ? ? ? ? and t.type = 'we' and t.delete = 1 ? ? </if> ? ? <if test="query == 0 and type = 2"> ? ? ? ? and t.type = 'wq' and t.delete = 1 ? ? </if> ? ? <if test="query == 0 and type = 3"> ? ? ? ? and t.type = 'wr' and t.delete = 1 ? ? </if> </where>
變現(xiàn)后:
select * from t_stu t <where> ? ? <if test="query == 0"> ? ? ? ? <if test="type = 1"> ? ? ? ? ? ? and t.type = 'we' ? ? ? ? </if> ? ? ? ? ?<if test="type = 2"> ? ? ? ? ? ? and t.type = 'wq' ? ? ? ? </if> ? ? ? ? <if test="type = 3"> ? ? ? ? ? ? and t.type = 'wr' ? ? ? ? </if> ? ? </if> ? ? and t.delete = 1 </where>
mybatis if-else寫(xiě)法
mybaits中沒(méi)有else要用chose when otherwise代替
<choose> ? ? <when test=""> ? ? ? ? //... ? ? </when> ? ? <otherwise> ? ? ? ? //... ? ? </otherwise> </choose>
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
springBoot Junit測(cè)試用例出現(xiàn)@Autowired不生效的解決
這篇文章主要介紹了springBoot Junit測(cè)試用例出現(xiàn)@Autowired不生效的解決,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-09-09SWT(JFace)體驗(yàn)之GridLayout布局
GridLayout 布局的功能非常強(qiáng)大,也是筆者常用的一種布局方式。GridLayout是網(wǎng)格式布局,它把父組件分成一個(gè)表格,默認(rèn)情況下每個(gè)子組件占據(jù)一個(gè)單元格的空間,每個(gè)子組件按添加到父組件的順序排列在表格中。2009-06-06spring cloud gateway 如何修改請(qǐng)求路徑Path
這篇文章主要介紹了spring cloud gateway 修改請(qǐng)求路徑Path的操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-06-06Spring boot配置多數(shù)據(jù)源代碼實(shí)例
這篇文章主要介紹了Spring boot配置多數(shù)據(jù)源代碼實(shí)例,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-07-07java實(shí)現(xiàn)文件復(fù)制、剪切文件和刪除示例
這篇文章主要介紹了java實(shí)現(xiàn)文件復(fù)制、剪切文件和刪除示例,需要的朋友可以參考下2014-04-04Java實(shí)現(xiàn)解數(shù)獨(dú)的小程序
最近在學(xué)習(xí)Java,然后上個(gè)月迷上了九宮格數(shù)獨(dú),玩了幾天,覺(jué)得實(shí)在有趣,就想著能不能用編程來(lái)解決,于是就自己寫(xiě)了個(gè),還真解決了。下面這篇文章就給大家主要介紹了Java實(shí)現(xiàn)解數(shù)獨(dú)的小程序,需要的朋友可以參考借鑒。2017-01-01深度解析Java中volatile的內(nèi)存語(yǔ)義實(shí)現(xiàn)以及運(yùn)用場(chǎng)景
這篇文章主要介紹了Java中volatile的內(nèi)存語(yǔ)義實(shí)現(xiàn)以及運(yùn)用場(chǎng)景,通過(guò)JVM的機(jī)制來(lái)分析volatile關(guān)鍵字在線(xiàn)程編程中的作用,需要的朋友可以參考下2015-12-12