當前位置:
首頁 > 知識 > 分享:Mybatis必會的動態SQL

分享:Mybatis必會的動態SQL

前言

Mybatis可謂是java開發者必須會的一項技能。MyBatis 的強大特性之一便是它的動態 SQL。如果你有使用 JDBC 或其它類似框架的經驗,你就能體會到根據不同條件拼接 SQL 語句的痛苦。例如拼接時要確保不能忘記添加必要的空格,還要注意去掉列表最後一個列名的逗號。利用動態 SQL 這一特性可以徹底擺脫這種痛苦。

Mybatis動態sql

mybatis 動態SQL,通過 if, choose, when, otherwise, trim, where, set, foreach等標籤,可組合成非常靈活的SQL語句,從而在提高 SQL 語句的準確性的同時,也大大提高了開發人員的效率。本文主要介紹這幾個動態SQL.

具體示例

if標籤 if就是用來對輸入映射的欄位進行判斷 一般是非空判斷 null 和。

!--案例1:動態sql之if--

selectid=selectUsersIfparameterType=userresultType=user

select*fromuserswhere1=1

iftest=uname!=nullanduname!=""andunamelike%#%/if

iftest=sex!=nullandsex!=""andsex=#/if

/select

動態SQL where / 相當於 where關鍵字 where /可以自動處理第一個前and 或者or。 當條件都沒有的時候 where也不會加上 。

!--案例2:動態sql之where可以自動處理第一個前and或者or。當條件都沒有的時候where也不會加上--

selectid=selectUsersWhereparameterType=userresultType=user

select*fromusers

where

iftest=uname!=nullanduname!=""andunamelike%#%/if

iftest=sex!=nullandsex!=""andsex=#/if

/where

choose—when--when--otherwise when可以多個 otherwise只能有一個 類似於 switch case。

需求:輸入用戶id 按照用戶id進行精確查找 其他條件不看 沒有輸入 id 用戶名模糊查找 都沒有的話 查詢id=1的用戶

!--案例3:動態sql之choose—whenwhenotherwise--

selectid=selectUsersChooseparameterType=userresultType=user

select*fromusers

where

choose

whentest=uid!=nulluid=#/when

whentest=uname!=nullanduname!=""unamelike%#%/when

otherwiseuid=1/otherwise

/choose

/where

/select

動態sql之set 代替set關鍵字 set標籤可以幫助我們去掉最後一個逗號

updateid=updateSetparameterType=user

updateusers

set

iftest=uname!=nullanduname!=""uname=#,/if

iftest=upwd!=nullandupwd!=""upwd=#,/if

iftest=sex!=nullandsex!=""sex=#,/if

iftest=birthday!=nullbirthday=#,/if

/set

whereuid=#

/update

Trim,trim代替where

!--案例5:動態sql之trim代替where--

selectid=selectUsersTrimWhereparameterType=userresultType=user

select*fromusers

!--

prefix:指添加前綴修飾

suffix:添加後綴修飾

prefixOverrides:去掉前綴修飾

suffixOverrides:去掉後綴修飾

--

trimprefix=whereprefixOverrides=and|or

iftest=uname!=nullanduname!=""andunamelike%#%/if

iftest=sex!=nullandsex!=""andsex=#/if

/trim

/select

Trim代替set:

!--案例6:動態sql之trim代替set--

updateid=updateTrimSetparameterType=user

updateusers

trimprefix=setsuffixOverrides=,suffix=whereuid=#

iftest=uname!=nullanduname!=""uname=#,/if

iftest=upwd!=nullandupwd!=""upwd=#,/if

iftest=sex!=nullandsex!=""sex=#,/if

iftest=birthday!=nullbirthday=#,/if

/trim

Foreach來遍歷集合

!--案例7:動態sql之foreach遍曆數組--

selectid=selectUsersForeachArrayresultType=user

select*fromuserswhereuidin

!--

collection:要遍歷的集合

item:當前正在遍歷的對象的變數名

open:開始遍歷

close:結束便利

index:下標

separator:分割

--

foreachcollection=arrayitem=itemopen=(close=)index=indexseparator=,

#

/foreach

/select

總結

熟練掌握以上Mysql的動態SQL,我們可以更得心應手的完成我的功能,寫更少的代碼,實現更多的功能。

喜歡這篇文章嗎?立刻分享出去讓更多人知道吧!

本站內容充實豐富,博大精深,小編精選每日熱門資訊,隨時更新,點擊「搶先收到最新資訊」瀏覽吧!


請您繼續閱讀更多來自 千鋒JAVA開發學院 的精彩文章:

使用AOP實現許可權攔截校驗
為什麼越來越多的程序員不願做做外包了

TAG:千鋒JAVA開發學院 |