<if>元素
<select id="selectUserByIf" resultType="com.po.MyUser" parameterType="com.po.MyUser">
select * from user where 1=1
<if test="uname !=null and uname!=''">
and uname like concat('%',#{uname},'%')
</if>
<if test="usex !=null and usex!=''">
and usex = #{usex}
</if>
</select>
<choose>、<when>、<otherwise>元素
<select id="selectUserByChoose" resultType="com.po.MyUser" parameterType="com.po.MyUser">
select * from user where 1=1
<choose>
<when test="uname !=null and uname!=''">
and uname like concat('%',#{uname},'%')
</when>
<when test="usex !=null and usex!=''">
and usex = #{usex}
</when>
<otherwise>
and uid > 10
</otherwise>
</choose>
<!--相当于switch-case-->
</select>
<trim>、<where>、<set>元素
<trim>元素的主要功能是可以在自己包含的内容前加上某些前缀,也可以在其后加上某些后缀,与之对应的属性是prefix和suffix;可以把包含内容的首部某些内容覆盖,即忽略,也可以把尾部的某些内容覆盖,对应的属性是prefixOverrides和suffixOverrides;正因为<trim>元素有这样的功能,所以也可以非常简单地利用<trim>来代替<where>元素的功能。
<!-- 使用trim元素,根据条件动态查询用户信息 -->
<select id="selectUserByTrim" resultType="com.po.MyUser" parameterType="com.po.MyUser">
select * from user
<trim prefix="where" prefixOverrides="and |or">
<if test="uname !=null and uname!=''">
and uname like concat('%',#{uname},'%')
</if>
<if test="usex !=null and usex!=''">
and usex = #{usex}
</if>
</trim>
</select>
<where>元素的作用是会在写入<where>元素的地方输出一个where语句,另外一个好处是不需要考虑<where>元素里面的条件输出是什么样子的,MyBatis将智能处理。如果所有的条件都不满足,那么MyBatis就会查出所有的记录,如果输出后是and 开头的,MyBatis会把第一个and忽略,当然如果是or开头的,MyBatis也会把它忽略;此外,在<where>元素中不需要考虑空格的问题,MyBatis将智能加上。
<!-- 使用where元素,根据条件动态查询用户信息 -->
<select id="selectUserByWhere" resultType="com.po.MyUser" parameterType="com.po.MyUser">
select * from user
<where>
<if test="uname !=null and uname!=''">
and uname like concat('%',#{uname},'%')
</if>
<if test="usex !=null and usex!=''">
and usex = #{usex}
</if>
</where>
</select>
在动态update语句中,可以使用<set>元素动态更新列
<!-- 使用set元素,动态修改一个用户 -->
<update id="updateUserBySet" parameterType="com.po.MyUser">
update user
<set>
<if test="uname != null">uname=#{uname},</if>
<if test="usex != null">usex=#{usex}</if>
</set>
where uid = #{uid}
</update>
<foreach>元素
<foreach>元素主要用在构建in条件中,它可以在SQL语句中进行迭代一个集合。foreach元素的属性主要有item,index,collection,open,separator,close。item表示集合中每一个元素进行迭代时的别名,index指定一个名字,用于表示在迭代过程中,每次迭代到的位置,open表示该语句以什么开始,separator表示在每次进行迭代之间以什么符号作为分隔符,close表示以什么结束。在使用<foreach>时,最关键的也是最容易出错的是collection属性,该属性是必选的,但在不同情况下,该属性的值是不一样的,主要有以下3种情况:
如果传入的是单参数且参数类型是一个List的时候,collection属性值为list。
如果传入的是单参数且参数类型是一个array数组的时候,collection的属性值为array。
如果传入的参数是多个时,需要把它们封装成一个Map,当然单参数也可以封装成Map。Map的key是参数名,collection属性值是传入的List或array对象在自己封装的Map中的key。
<!-- 使用foreach元素,查询用户信息 -->
<select id="selectUserByForeach" resultType="com.po.MyUser" parameterType="List">
select * from user where uid in
<foreach item="item" index="index" collection="list" open="(" separator="," close=")">
#{item}
</foreach>
</select>