动态 Sql 的辅助元素
where、set、trim 作为动态 Sql 的辅助元素,起作用是处理 sql 的封装问题
<where>
常与 <select> 搭配使用
<select id="selectIfandWhereOper" resultMap="BaseResultMap">
select
<include refid="Base_Column_List" />
from t_user a
<where>
<if test="email != null and email != ''">
and a.email like CONCAT('%', #{email}, '%')
</if>
<if test="sex != null ">
and a.sex = #{sex}
</if>
</where>
</select>
<where> 有2个作用:
- <where> </where>内有 <if> 成立时,加上 where 关键字
- 去掉第一个 <if> </if>里的 and 或者 or
<set>
常与 <update> 搭配使用
<update id="updateByPrimaryKeySelective" parameterType="TUser">
update t_user
<set>
<if test="userName != null">
userName = #{userName,jdbcType=VARCHAR},
</if>
<if test="realName != null">
realName = #{realName,jdbcType=VARCHAR},
</if>
<if test="sex != null">
sex = #{sex,jdbcType=TINYINT},
</if>
</set>
where id = #{id,jdbcType=INTEGER}
</update>
<set> 有2个作用:
- 加上 set 关键字
- 去掉最后一个 <if> </if> 里的逗号
<trim>
常与 <insert> 搭配使用
<insert id="insertSelective" parameterType="TUser" useGeneratedKeys="true" keyProperty="id">
insert into t_user
<trim prefix="(" suffix=")" suffixOverrides="," >
<if test="id != null">
id,
</if>
<if test="userName != null">
userName,
</if>
<if test="realName != null">
realName,
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="id != null">
#{id,jdbcType=INTEGER},
</if>
<if test="userName != null">
#{userName,jdbcType=VARCHAR},
</if>
<if test="realName != null">
#{realName,jdbcType=VARCHAR},
</trim>
</insert>
<trim> 有2个作用:
- prefix="(" suffix=")" 让前后加上了括号
- suffixOverrides="," 去掉最后一个逗号
可以用<trim>表达<where>:
<trim prefix="where" prefixOverrides="and | or ">
神奇的是,和使用 <where> 一样,如果 <if> </if>都不成立,会没有 where 关键字。
但是上面的 prefix="(" suffix=")" ,如果 <if> </if>都不成立,也会有 “(” 和 “)”。