案例一(where和if的使用):根据名字和成绩来查询人数,名字为模糊查询。
<select id="total" resultType="Integer">
select count(*) from student
<where>
<if test="name!=null and name!=''">and name like concat('%',#{name},'%')</if>
<if test="score!= null and score>=0">and score = #{score}</if>
</where>
</select>
注意,where的作用在于可以在if语句都为空时,才会拼接SQL语句。不在需要之前的where 1=1。
案例二(choose,when,otherwize的使用):
与案例一不同的是,案例一是只要test属性表达式为true,那么就会执行SQL语句。但是,当我们需要从多个条件中只选一个条件执行时(即使可能多个条件满足,比如我们Java中的Switch...catch...default),那么我们就可以用这些元素。
<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>
本案例是使用了choose元素进行SQL语句的拼装,当第一个when为true时就只拼装第一个,否则判断第二个,以此类推。如果所有的when都为false,那么就只拼装otherwise。
案例三(trim,where的使用):
<select id="queryByName" parameterType="Map" resultMap="studentMap">
select * from `student`
<trim prefix="where" prefixOverrides="and">
<if test="name!=null and name!=''">and name like concat('%',#{name},'%')</if>
</trim>
limit #{start},#{end}
</select>
注意,当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>
注意,当test语句都不满足时,不会被组装。
案例五(foreach的使用):
<delete id="deleteMore">
delete from student where id in
<foreach collection="list" item="item_id" separator="," open="(" close=")">
#{item_id}
</foreach>
</delete>
比如这里的批量删除。
案例六(bind的使用):
<select id="selectBlogsLike" resultType="Blog">
<bind name="pattern" value="'%' + _parameter.getTitle() + '%'" />
SELECT * FROM BLOG
WHERE title LIKE #{pattern}
</select>
它的方便性一个时可以进行文本代替,另一个是便于移植。