動態 SQLdom
if 條件判斷ide
<select id="findActiveBlogLike" resultType="Blog"> SELECT * FROM BLOG WHERE state = ‘ACTIVE’ <if test="title != null"> AND title like #{title} </if> <if test="author != null and author.name != null"> AND author_name like #{author.name} </if> </select>
choose (when, otherwise)條件查詢code
<select id="findActiveBlogLike" resultType="Blog"> SELECT * FROM BLOG WHERE state = ‘ACTIVE’ <choose> <when test="title != null"> AND title like #{title} </when> <when test="author != null and author.name != null"> AND author_name like #{author.name} </when> <otherwise> AND featured = 1 </otherwise> </choose> </select>
trim (where, set)xml
where:元素只會在至少有一個子元素的條件返回 SQL 子句的狀況下才去插入「WHERE」子句。並且,若語句的開頭爲「AND」或「OR」,where 元素也會將它們去除。blog
<select id="findActiveBlogLike" 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 and author.name != null"> AND author_name like #{author.name} </if> </where> </select>
trim:經過自定義 trim 元素來定製 where 元素的功能get
<trim prefix="WHERE" prefixOverrides="AND |OR "> ... </trim>
set:元素能夠用於動態包含須要更新的列,而捨去其它的it
<update id="updateAuthorIfNecessary"> 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>
foreach:對一個集合進行遍歷,一般是在構建 IN 條件語句的時候io
<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>
bind:元素能夠從 OGNL 表達式中建立一個變量並將其綁定到上下文class
<select id="selectBlogsLike" resultType="Blog"> <bind name="pattern" value="'%' + _parameter.getTitle() + '%'" /> SELECT * FROM BLOG WHERE title LIKE #{pattern} </select>