ibatis 3 學習筆記 5
動態sql語句
可以在xml檔案中新增條件配置來動態拼接,呼叫sql語句
ibatis使用的ONGL表示式有四種元素
if
choose
trim
foreach
if
<select id=”findActiveBlogLike” parameterType=”Blog” resultType=”Blog”> SELECT * FROM BLOG WHERE state = ‘ACTIVE’ <if test=”title != null”> AND title like #{title} if> <if test=”author!= null && author.name != null”> AND title like #{author.name} if> select>
choose,when,otherwise
<select id=”findActiveBlogLike” parameterType=”Blog” resultType=”Blog”> SELECT * FROM BLOG WHERE state = ‘ACTIVE’ <choose> <when test=”title != null”>AND title like #{title} when> <when test=”author != null && author.name != null”> AND title like #{author.name} when> <otherwise> AND featured = 1 otherwise> choose> select>
trim,where,set
where標籤可以動態加上where關鍵字:
<select id=”findActiveBlogLike”
parameterType=”Blog” resultType=”Blog”>
SELECT * FROM BLOG
<where>
<if test=”state != null”>
state = #{state}
if>
<if test=”title != null”>
AND title like #{title}
if>
<if test=”author != null && author.name != null”>
AND title like #{author.name}
if>
where>
select>
這裡也可以自定義trim元素來控制where等關鍵字,下面的trim配置等價於where標籤
<trim prefix="WHERE" prefixOverrides="AND |OR "> … trim>
這裡trim標籤文件上敘述的很模糊,大概意思是如果trim內的字元帶有字首“AND ”或者“OR ”那麼去掉trim整段字元前面的where,否則新增where。
來看update語句中:
<update id="updateAuthorIfNecessary" parameterType="domain.blog.Author"> update Author <set> <if test="username != null">username=#{username},if> <if test="password != null">password=#{password},if> <if test="email != null">email=#{email},if> <if test="bio != null">bio=#{bio}if> set> where id=#{id} update>
set標籤等價的trim標籤配置為
<trim prefix="SET" suffixOverrides=","> … trim>
這裡的trim標籤原文敘述的很模糊,大概意思是trim中的字元帶有後綴,的話那麼就去掉trim整段字元前的set,否則新增set
foreach
<select id="selectPostIn" resultType="domain.blog.Post"> SELECT * FROM POST P WHERE ID in <foreach item="item" index="index" collection="list" open="(" separator="," close=")"> #{item} foreach> select>
基本能明白foreach標籤的作用了:
item說明了集合內每一個元素的值,並在下面的sql中使用#{item} 來引用這個值
index說明了集合內每一個元素的下標,並在下面的sql中使用#{index} 來引用這個值
collection說明了集合元素的型別
open是指轉換後前面新增(
separator表示每個集合元素之間以“,”分隔
close在轉換後最後新增)。