動態SQL
阿新 • • 發佈:2017-09-04
字符串類型 屬性 pre find tty where 1=1 cnblogs images index
If:註意要做不等於空字符串校驗
<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>
Where:<where />可以自動處理第一個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>
foreach:向sql傳遞數組或List,mybatis使用foreach解析
1)通過pojo傳遞list
<if test="ids!=null and ids.size>0"> <foreach collection="ids" open=" and id in(" close=")" item="id" separator="," > #{id} </foreach> </if>
2)傳遞單個List
<select id="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>
3)傳遞單個數組(數組中是pojo)
<select id="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:中間分隔輸出
4)傳遞單個數組(數組中是字符串類型,如果數組中是簡單類型則寫為#{item},不用再通過ognl獲取對象屬性值了)
<select id="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>
Sql片段
Sql中可將重復的sql提取出來,使用時用include引用即可,最終達到sql重用的目的
動態SQL