mybatis中的if-else及if嵌套使用方式
if-else及if嵌套使用方式
案例一:if-else
在使用mybatis mapper 動態(tài)sql時,不免會出現(xiàn)if-else的使用,但是好像又沒有這種語法,提供的是choose標簽代替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>
也可以用多個if判斷實現(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嵌套
在實際編碼過程中會有一些判斷條件會一直重復使用,一直寫在if標簽中寫的代碼會特長,而且臃腫
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寫法
mybaits中沒有else要用chose when otherwise代替
<choose> ? ? <when test=""> ? ? ? ? //... ? ? </when> ? ? <otherwise> ? ? ? ? //... ? ? </otherwise> </choose>
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
springBoot Junit測試用例出現(xiàn)@Autowired不生效的解決
這篇文章主要介紹了springBoot Junit測試用例出現(xiàn)@Autowired不生效的解決,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-09-09spring cloud gateway 如何修改請求路徑Path
這篇文章主要介紹了spring cloud gateway 修改請求路徑Path的操作,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-06-06Spring boot配置多數(shù)據(jù)源代碼實例
這篇文章主要介紹了Spring boot配置多數(shù)據(jù)源代碼實例,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2020-07-07深度解析Java中volatile的內(nèi)存語義實現(xiàn)以及運用場景
這篇文章主要介紹了Java中volatile的內(nèi)存語義實現(xiàn)以及運用場景,通過JVM的機制來分析volatile關(guān)鍵字在線程編程中的作用,需要的朋友可以參考下2015-12-12