注:xxx为某某某的意思
update xxx
<set>
<if test="xx !=null and xx !='' ">
SQL1,
</if>
<if test="x !=null and x !='' ">
SQL2,
</if>
</set>
where SQL3
如果<if test="xx !=null and xx !='' ">成立,<if test="x !=null and x !='' ">不成立
则最终SQL语句为 update xxx set SQL1 where SQL3;
<set>会自动去掉SQL1,尾部的逗号,并加上set
如果均成立
则最终SQL语句为 update xxx set SQL1, SQL2 where SQL3;
实际例子
UPDATE table_name SET column1 = value1, column2 = value2 WHERE id=36;
逗号<set>里判断后结果不能为空,否则SQL语句语法错误
对于<set>,同<where>一样可以用<trim>代替
update xxx
<trim prefix="set" suffixOverrides=",">
<if test="xx !=null and xx !='' ">
SQL1,
</if>
<if test="x !=null and x !='' ">
SQL2,
</if>
</trim>
where SQL3
完整例子
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.xxx.xxx.xxxMapper">
<update id="updateXxxBySet"
parameterType="com.xxx.xxx.xxx">
update xxx
<set>
<if test="xx !=null and xx !='' ">
SQL1,
</if>
<if test="x !=null and x !='' ">
SQL2,
</if>
</set>
where SQL3
</update>
<update id="updateXxxBySetTRIM"
parameterType="com.xxx.xxx.xxx">
update xxx
<trim prefix="set" suffixOverrides=",">
<if test="xx !=null and xx !='' ">
SQL1,
</if>
<if test="x !=null and x !='' ">
SQL2,
</if>
</trim>
where SQL3
</update>
</mapper>