MyBatis的動態SQL是基于OGNL表達式的,它可以幫助我們方便的在SQL語句中實現某些邏輯。
MyBatis中用于實現動態SQL的元素主要有:
mybatis核心 對sql語句進行靈活操作,通過表達式進行判斷,對sql進行靈活拼接、組裝。
1、statement中直接定義使用動態SQL:
在statement中利用if 和 where 條件組合達到我們的需求,通過一個例子來說明:
原SQL語句:
1
2
3
4
|
< select id= "findUserByUserQuveryVo" parameterType = "UserQueryVo" resultType= "UserCustom" > select * from user where username = #{userCustom.username} and sex = #{userCustom.sex} </ select > |
現在需求是,如果返回值UserCustom為空或者UserCustom中的屬性值為空的話(在這里就是userCustom.username或者userCustom.sex)為空的話我們怎么進行靈活的處理是程序不報異常。做法利用if和where判斷進行SQL拼接。
1
2
3
4
5
6
7
8
9
10
11
12
13
|
< select id= "findUserByUserQuveryVo" parameterType = "UserQueryVo" resultType= "UserCustom" > select * from user < where > <if test= "userCustom != null" > <if test= "userCustom.username != null and userCustom.username != ''" ><! -- 注意and不能大寫 --> and username = #{userCustom.username} </if> <if test= "userCustom.sex != null and userCustom.sex != ''" > and sex = #{userCustom.sex} </if> </if> </ where > </ select > |
有時候我們經常使用where 1=1這條語句來處理第一條拼接語句,我們可以使用< where > < where />來同樣實現這一功能。
2、使用sql片段來處理statement
和我們寫程序一樣,有時候會出現一些重復的代碼,我們可以用SQL片段來處理。在sql片段中需要注意的是它的位置,我們也可以引用其它mapper文件里面的片段,此時需要我們定義它的位置。
(1)、sql片段的定義
1
2
3
4
5
6
7
8
|
<sql id= "query_user_where" > <if test= "sex != null and sex != ''" > and sex = #{sex} </if> <if test= "id != null" > and id = #{id} </if> </sql> |
(2)、sql片段的使用
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
< select id= "findUserList" parameterType= "User" resultType= "User" > select * from user < where > <! -- 引用Sql片段 --> <include refid= "query_user_where" ></include> <! -- 在這里還要引用其它的sql片段 --> <! -- where 可以自動去掉條件中的第一個 and --> <! -- <if test="sex != null and sex != ''"> and sex = #{sex} </if> <if test= "id != null" > and id = #{id} </if> --> </ where > </ select > |
3、使用foreach進行sql語句拼接
在向sql傳遞數組或List,mybatis使用foreach解析,我們可以使用foreach中元素進行sql語句的拼接,請求數據。
通過一個例子來看:
需求:SELECT * FROM USER WHERE id=1 OR id=10 OR id=16
或者:SELECT * FROM USER WHERE id IN(1,10,16)
1
2
3
4
5
6
|
<if test= "ids != null" > <foreach collection= "ids" item= "user_id" open = "AND (" close = ")" separator= "or" > 每次遍歷需要拼接的串 id= #{user_id} </foreach> </if> |
其中,collection:指定輸入對象中集合屬性,item: 每個遍歷生成對象,open:開始遍歷時拼接串,close: 結束遍歷是拼接的串,separator: 遍歷的兩個對象中需要拼接的串
1
2
3
4
5
|
<if test= "ids != null" > <foreach collection= "ids" item= "user_id" open = "and id IN(" close = ")" separator= "," > id= #{user_id} </foreach> </if> |
總結
以上所述是小編給大家介紹的Mybatis中動態SQL,if,where,foreach的使用教程,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對服務器之家網站的支持!
原文鏈接:https://www.2cto.com/database/201711/696473.html