多条件只生效一个
<choose>
<when test="title != null">
AND title like #{title}
</when>
<when test="author != null ">
AND author_name like #{author.name}
</when>
<otherwise>
AND featured = 1
</otherwise>
</choose>
动态SQL注入查询
<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>
where在有条件生效的情况下,会自动去除开头多余的“AND” 或 “OR”
<trim prefix="WHERE" prefixOverrides="AND |OR "></trim> prefix:条件生效的情况下,开头提交的标签,prefixOverrides去除开头多余的标签(注意此例中的空格是必要的)
动态SQLupdate
<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>
<trim prefix="SET" suffixOverrides=","> ... </trim>
prefix:添加前缀字段,suffixOverrides:去除尾部多余字段
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>
index:索引,item是值,collection:集合