动态SQL通过下面四个功能展开:
1.if
<select id="Query" resultType="Blog">
SELECT * FROM BLOG
WHERE 1=1
<if test="title != null">
AND title like #{title}
</if>
</select>
1=1是预定义操作,给后面的AND提供拼接基础。也可以用后面介绍的where
若传入了“title”,那么就会对“title”一列进行模糊查找,如果没有就算了。
2.choose, when, otherwise
类似switch语句
<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>
3.trim, where, set
where实例:
<select id="findActiveBlogLike" resultType="Blog">
SELECT * FROM BLOG
<where>
<if test="state != null">
state = #{state}
</if>
</where>
</select>
trim是给where不灵的时候用的
<trim prefix="WHERE" prefixOverrides="AND |OR ">
...
</trim>
set是动态更新语句的解决方案
<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>
4.foreach
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>
大成功!