【Mybatis】深入淺出Mybatis(八)——動態SQL
一、前言
前一篇部落格中介紹了Mybatis的別名的使用,這個方法也是非常方便的。下面小編向大家介紹一下Mybatis的最精彩的亮點——動態SQL。通過mybatis提供的各種標籤方法實現動態拼接sql。
二、if
if標籤可以起到判斷的作用,用來判斷我們所要查詢的欄位是否為空或者是‘’,可以讓sql語句更加的靈活。提高了複用性。
PS:注意要做不等於空字串校驗。
<!-- 傳遞pojo綜合查詢使用者資訊 -->
<select id="findUserList" parameterType="user" resultType ="user">
select * from user
where 1=1
<if test="id!=null and id!=''">
and id=#{id}
</if>
<if test="username!=null and username!=''">
and username like '%${username}%'
</if>
</select>
如果條件都成立的話,最終的sql語句就是:
select * from user where id=#{id} and username like '%${username}%'
三、Where
Mybatis提供了where,可以自動處理第一個and。
比如在下面的例子中,如果id為不為空或者不為‘’,會自動的判斷是否需要and,如果需要的話就補上,如果不需要,Mybatis就自動去掉and。
<select id="findUserList" parameterType="user" resultType="user">
select * from user
<where >
<if test="id!=null and id!=''">
and id=#{id}
</if>
<if test="username!=null and username!=''">
and username like '%${username}%'
</if>
</where>
</select>
如果條件都成立的話,最終的sql語句就是:
select * from user where id=#{id} and username like '%${username}%'
四、foreach
向sql傳遞陣列或List,mybatis使用foreach解析
在使用者查詢列表和查詢總數的statement中增加多個id輸入查詢。
sql語句如下:
兩種方法:
SELECT * FROM USER WHERE id=1 OR id=10 OR id=16
SELECT * FROM USER WHERE id IN(1,10,16)
使用 foreach遍歷傳入ids,他有下面的標籤:
collection:指定輸入 物件中集合屬性
item:每個遍歷生成物件中
open:開始遍歷時拼接的串
close:結束遍歷時拼接的串
separator:遍歷的兩個物件中需要拼接的串
實踐程式碼如下:
<if test="ids!=null">
<!-- 使用 foreach遍歷傳入ids
collection:指定輸入 物件中集合屬性
item:每個遍歷生成物件中
open:開始遍歷時拼接的串
close:結束遍歷時拼接的串
separator:遍歷的兩個物件中需要拼接的串
-->
<!-- 使用實現下邊的sql拼接:
AND (id=1 OR id=10 OR id=16)
-->
<foreach collection="ids" item="user_id" open="AND (" close=")" separator="or">
<!-- 每個遍歷需要拼接的串 -->
id=#{user_id}
</foreach>
<!-- 實現 “ and id IN(1,10,16)”拼接 -->
<!-- <foreach collection="ids" item="user_id" open="and id IN(" close=")" separator=",">
每個遍歷需要拼接的串
#{user_id}
</foreach> -->
</if>
五、sql片段
我們可以把上面實現的動態sql判斷程式碼塊抽取出來,組成一個sql片段。當其他的statement中需要,就可以引用sql片段了。這樣sql程式碼的複用率就提高了,程式設計師開發就更加的方便了。
Sql中可將重複的sql提取出來,使用時用include引用即可,最終達到sql重用的目的,如下:
<!-- 傳遞pojo綜合查詢使用者資訊 -->
<select id="findUserList" parameterType="user" resultType="user">
select * from user
<where>
<if test="id!=null and id!=''">
and id=#{id}
</if>
<if test="username!=null and username!=''">
and username like '%${username}%'
</if>
</where>
</select>
將where條件抽取出來:
<sql id="query_user_where">
<if test="id!=null and id!=''">
and id=#{id}
</if>
<if test="username!=null and username!=''">
and username like '%${username}%'
</if>
</sql>
Sql片段的引用,使用include引用:
<select id="findUserList" parameterType="user" resultType="user">
select * from user
<where>
<include refid="query_user_where"/>
</where>
</select>
注意:如果引用其它mapper.xml的sql片段,則在引用時需要加上namespace,如下:
六、小結
動態SQL就是複用sql語句的過程。
要想體驗到這個過程,就必須要多多的嘗試一下,必須多多的鍛鍊,多用,才能把Mybatis的好處發揮到極致。
下一篇部落格向大家帶來“深入淺出Mybatis(九)——Mybatis和hibernate的對比”;