trim标签的属性:
- prefix: 拼接sql需要加上的前缀。
- prefixOverrides:前缀需要覆盖消除的内容。
- suffix:拼接sql需要加上的后缀
- suffixOverrides:后缀需要覆盖消除的内容
例子:
有下面sql语句
select *from user where username = ? and password = ? and role = ?
trim标签写法如下
<select id="selectUser" parameterType="User" resultType="User">
select *from user
<where>
<trim prefixOverrides="and">
<if test="username != null and username != ''"> and username = #{name}</if>
<if test = "password != null and password != ''">and password = #{password}</if>
<if test = "role != null and role != ''">and role = #{role}</if>
</trim>
</where>
</select>
insert into user (id, username,password,birthday,role) values (?,?,?,?,?)
trim标签写法如下
<insert id="insertUser" parameterType="User" >
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="id != null and id != ''">id,</if>
<if test="username != null and username != ''">username,</if>
<if test="password != null and password != ''">password ,</if>
<if test="birthday!= null and birthday != ''">birthday,</if>
<if test="role != null and role != ''">role,</if>
</trim>
<trim prefix=" values (" suffix=")" suffixOverrides=",">
<if test="id != null and id != ''">#{id},</if>
<if test="username != null and username != ''">#{username},</if>
<if test="password != null and password != ''">#{password},</if>
<if test="birthday!= null and birthday != ''">#{birthday},</if>
<if test="role != null and role != ''">#{role},</if>
</trim>
</insert>
update user set username = ?,password = ?,role = ? where id = ?
<update id="updateUser" parameterType="User">
update user
<set>
<trim suffixOverrides=",">
<if test="id != null and id != ''">id,</if>
<if test="username != null and username != ''">username,</if>
<if test="password != null and password != ''">password ,</if>
<if test="birthday!= null and birthday != ''">birthday,</if>
<if test="role != null and role != ''">role,</if>
</trim>
</set>
where id = #{id}
</update>