MyBatis中使用Update的set和if

@MyBatis中使用Update的set和if

		UPDATE service_accountuser
		<set>
			<if test="username != null and username != ''">
				username = #{username},
			</if>
			<if test="userPhone != null and userPhone != ''">
				userPhone = #{userPhone},
			</if>
			<if test="userBrithday != null and userBrithday != ''">
				userBrithday = #{userBrithday},
			</if>
			<if test="realName != null and realName != ''">
				realName = #{realName},
			</if>
			<if test="userEmail != null and userEmail != ''">
				userEmail =#{userEmail},
			</if>
			<if test="userSex != null and userSex != ''">
				userSex = #{userSex},
			</if>
			<if test="remarks != null and remarks != ''">
				remarks = #{remarks},
			</if>
		</set>
		WHERE id = #{id}
	</update>

update中的set一定要写成<set></set>
的形式,这样才会自动去掉SQL语句中(where关键字前)的最后一个,

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
示例: 假设有一个User表,有一个字段为status,需要更新多条记录的status值为1,更新的记录id为1、2、3,可以使用以下代码: ``` <update id="updateUserStatus"> UPDATE User SET status = 1 <where> <foreach collection="ids" item="id" separator="OR"> id = #{id} </foreach> </where> </update> ``` 其,ids为一个List类型的参数,存储需要更新的记录的id值。在where标签内使用foreach标签循环遍历ids的id值,将每个id值拼接为OR条件,最终得到的sql语句如下: ``` UPDATE User SET status = 1 WHERE id = 1 OR id = 2 OR id = 3 ``` 如果需要更新多个字段,可以使用set标签,示例代码如下: ``` <update id="updateUser"> UPDATE User <set> <foreach collection="params" item="param" separator=","> <if test="param.name != null">name = #{param.name}</if> <if test="param.age != null">age = #{param.age}</if> <if test="param.tel != null">tel = #{param.tel}</if> </foreach> </set> <where> <foreach collection="ids" item="id" separator="OR"> id = #{id} </foreach> </where> </update> ``` 其,params为一个List类型的参数,存储需要更新的字段和值,示例代码更新的字段为name、age、tel。在set标签内使用foreach标签循环遍历params的每个param对象,如果该字段不为null,则拼接为update语句的一个字段更新语句。最终得到的sql语句如下: ``` UPDATE User SET name = 'xxx', age = 20, tel = 'xxx' WHERE id = 1 OR id = 2 OR id = 3 ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值