http://haohaoxuexi.iteye.com/blog/1338557
MyBatis的動態SQL是基於OGNL表達式的,它可以幫助我們方便的在SQL語句中實現某些邏輯。
MyBatis中用於實現動態SQL的元素主要有:
- if
- choose(when,otherwise)
- trim
- where
- set
- foreach
if
- <select id="dynamicIfTest" parameterType="Blog" resultType="Blog">
- select * from t_blog where 11 = 1
- <if test="title != null">
- and title = #{title}
- </if>
- <if test="content != null">
- and content = #{content}
- </if>
- <if test="owner != null">
- and owner = #{owner}
- </if>
- </select>
choose
- <select id="dynamicChooseTest" parameterType="Blog" resultType="Blog">
- select * from t_blog where 11 = 1
- <choose>
- <when test="title != null">
- and title = #{title}
- </when>
- <when test="content != null">
- and content = #{content}
- </when>
- <otherwise>
- and owner = "owner1"
- </otherwise>
- </choose>
- </select>
where
- <select id="dynamicWhereTest" parameterType="Blog" resultType="Blog">
- select * from t_blog
- <where>
- <if test="title != null">
- title = #{title}
- </if>
- <if test="content != null">
- and content = #{content}
- </if>
- <if test="owner != null">
- and owner = #{owner}
- </if>
- </where>
- </select>
trim
- <select id="dynamicTrimTest" parameterType="Blog" resultType="Blog">
- select * from t_blog
- <trim prefix="where" prefixOverrides="and |or">
- <if test="title != null">
- title = #{title}
- </if>
- <if test="content != null">
- and content = #{content}
- </if>
- <if test="owner != null">
- or owner = #{owner}
- </if>
- </trim>
- </select>
set
- <update id="dynamicSetTest" parameterType="Blog">
- update t_blog
- <set>
- <if test="title != null">
- title = #{title},
- </if>
- <if test="content != null">
- content = #{content},
- </if>
- <if test="owner != null">
- owner = #{owner}
- </if>
- </set>
- where id = #{id}
- </update>
foreach
- 如果傳入的是單參數且參數類型是一個List的時候,collection屬性值爲list
- 如果傳入的是單參數且參數類型是一個array數組的時候,collection的屬性值爲array
- 如果傳入的參數是多個的時候,我們就需要把它們封裝成一個Map了,當然單參數也可以封裝成map,實際上如果你在傳入參數的時候,在MyBatis裏面也是會把它封裝成一個Map的,map的key就是參數名,所以這個時候collection屬性值就是傳入的List或array對象在自己封裝的map裏面的key
- <select id="dynamicForeachTest" resultType="Blog">
- select * from t_blog where id in
- <foreach collection="list" index="index" item="item" open="(" separator="," close=")">
- #{item}
- </foreach>
- </select>
- <select id="dynamicForeach2Test" resultType="Blog">
- select * from t_blog where id in
- <foreach collection="array" index="index" item="item" open="(" separator="," close=")">
- #{item}
- </foreach>
- </select>