Mybatis中trim标签的用法

时间:2021-08-27 23:29:30
select * from t_user
<trim prefix="WHERE" prefixOverrides="and">
  <if test="roleName != null and roleName != ''"> AND role_name=#{roleName}</if>
</trim>

如果条件成立并且没有trim标签,那么sql语句就为

select * from t_user AND role_name=#{roleName}

现在有了trim标签,prefix表示在红色代码前面添加where,prefixoverride表示把最前面的and删除.那么代码就变为

select * from t_user WHERE role_name=#{roleName}

update t_role
<trim prefix="SET" suffixOverrides=",">
<if test="roleName != null and roleName != ''"> role_name=#{roleName},</if>
<if test="note != null and note != ''"> role_name=#{roleName},</if>
</trim>
where role_no = #{roleNo}

如果条件成立并且没有trim标签,那么sql语句就为

update t_role role_name=#{roleName},role_name=#{roleName}, where role_no=#{roleNo}

现在有了trim标签,prefix表示在红色代码前面添加set,suffixOverrides表示把末尾的','删除.那么代码就变为

update t_role SET role_name=#{roleName},role_name=#{roleName} where role_no=#{roleNo}