前記:這是很早之前自學學習myBatis時的筆記,內容比較基礎,適合新手,內容基本是來自網絡,如有雷同,敬請諒解!
動態Sql
mybatis核心 對sql語句進行靈活操作,通過表達式進行判斷,對sql進行靈活拼接、組裝。
if的使用
!-- 傳遞pojo綜合查詢用戶信息 -->
<selectid="findUserList”parameterType="user"resultType="user">
select * from user
where 1=1
<if test="id!=null and id!=''">
and id=#{id}
</if>
<if test="username!=nulland username!=''">
and username like '%${username}%'
</if>
</select>
注意要做不等於空字符串校驗
where的使用
上面的sql也可以改爲:
<selectid="findUserList"parameterType="user"resultType="user">
select * from user
<where>
<if test="id!=nulland id!=''">
and id=#{id}
</if>
<if test="username!=nulland username!=''">
and username like '%${username}%'
</if>
</where>
</select>
<where />可以自動處理第一個and。
foreach的使用
向sql傳遞數組或List,mybatis使用foreach解析
通過pojo傳遞list
在pojo中定義list屬性ids存儲多個用戶id,並添加getter/setter方法
mapper.xml
<iftest="ids!=null and ids.size>0">
<foreach collection="ids"open=" and idin("close=")" item="id" separator=",">
#{id}
</foreach>
</if>
或者:
傳遞單個list
傳遞List類型在編寫mapper.xml沒有區別,唯一不同的是隻有一個List參數時它的參數名爲list。
如下:
Mapper.xml
<selectid="selectUserByList"
parameterType="java.util.List"
resultType="user">
select * from user
<where>
<!-- 傳遞List,List中是pojo -->
<if test="list!=null">
<foreach collection="list"item="item"open="and id in("separator=","close=")">
#{item.id}
</foreach>
</if>
</where>
</select>
Mapper接口
public List<User>selectUserByList(List userlist) throws Exception;
傳遞單個數組(數組中是pojo)
Mapper.xml
<!-- 傳遞數組綜合查詢用戶信息 -->
<selectid="selectUserByArray" parameterType="Object[]" resultType="user">
select * from user
<where>
<!-- 傳遞數組 -->
<if test="array!=null">
<foreach collection="array" index="index" item="item" open="and id in(" separator="," close=")">
#{item.id}
</foreach>
</if>
</where>
</select>
sql只接收一個數組參數,這時sql解析參數的名稱mybatis固定爲array,
如果數組是通過一個pojo傳遞到sql則參數的名稱爲pojo中的屬性名。
index:爲數組的下標。
item:爲數組每個元素的名稱,名稱隨意定義
open:循環開始
close:循環結束
separator:中間分隔輸出
傳遞單個數組(數組中是字符串類型)
Mapper.xml
<!-- 傳遞數組綜合查詢用戶信息 -->
<selectid="selectUserByArray" parameterType="Object[]" resultType="user">
select * from user
<where>
<!-- 傳遞數組 -->
<if test="array!=null">
<foreach collection="array" index="index" item="item" open="and id in(" separator="," close=")">
#{item}
</foreach>
</if>
</where>
</select>
如果數組中是簡單類型則寫爲#{item},不用再通過ognl獲取對象屬性值了。
Sql片段
Sql中可將重複的sql提取出來,使用時用include引用即可,最終達到sql重用的目的,如下:
<!-- 傳遞pojo綜合查詢用戶信息 -->
<selectid="findUserList"parameterType="user"resultType="user">
select * from user
<where>
<if test="id!=null and id!=''">
and id=#{id}
</if>
<if test="username!=nul land username!=''">
and username like '%${username}%'
</if>
</where>
</select>
將where條件抽取出來:
<sqlid="query_user_where">
<iftest="id!=null and id!=''">
and id=#{id}
</if>
<iftest="username!=null and username!=''">
and username like '%${username}%'
</if>
</sql>
使用include引用:
<selectid="findUserList"parameterType="user"resultType="user">
select * from user
<where>
<include refid="query_user_where"/>
</where>
</select>
注意:如果引用其它mapper.xml的sql片段,則在引用時需要加上namespace,如下:
<includerefid="namespace.sql片段”/>