mybatis中的if-else及if嵌套使用方式
更新時間:2022年03月23日 09:55:58 作者:小小猴沖刺
這篇文章主要介紹了mybatis中的if-else及if嵌套使用方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
if-else及if嵌套使用方式
案例一:if-else
在使用mybatis mapper 動態(tài)sql時,不免會出現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判斷實現:
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>
變現后:
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>
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
springBoot Junit測試用例出現@Autowired不生效的解決
這篇文章主要介紹了springBoot Junit測試用例出現@Autowired不生效的解決,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-09-09spring cloud gateway 如何修改請求路徑Path
這篇文章主要介紹了spring cloud gateway 修改請求路徑Path的操作,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-06-06深度解析Java中volatile的內存語義實現以及運用場景
這篇文章主要介紹了Java中volatile的內存語義實現以及運用場景,通過JVM的機制來分析volatile關鍵字在線程編程中的作用,需要的朋友可以參考下2015-12-12