写于20210618 21:00 北京望京
数据库
借于不少人不会 mybatis 批量更新,特此记录。bash
微信搜:JavaPub ,有疑惑留言。微信
当咱们在作更新或者是插入操做时,数据为多对多、一一对应的状况markdown
例如:mybatis
编号。 名字。 状态 1。 tom 0 2。 jerry. 0 3。 jeck. 1
代码中循环写入、更新这是大多数人作法,可是确定不是最优解ide
这里数据库中存储了下划线式,代码中用驼峰式。atom
这里是经过userId修改userStatus。当user_id为1时、user_status为0,当user_id为3时、user_status为1。spa
<update id="updateBatch"> update <include refid="tableName"/> <trim prefix="set" suffixOverrides=","> <trim prefix="user_status =case" suffix="end,"> <foreach collection="list" item="i" index="index"> <if test="i.userId!=null"> when user_id=#{i.userId} then #{i.userStatus} </if> </foreach> </trim> </trim> where user_id in <foreach collection="list" item="i" index="index" open="(" separator="," close=")"> #{i.userId} </foreach> </update>
<trim 属性说明.net
可是你们要注意一点,这种状况若是出错,咱们并不知道是哪条错误,若是使用事务,就会所有回滚,好的办法就是一次批量一部分,分担出错几率。code
参考: https://blog.csdn.net/lu1024188315/article/details/78758943 https://blog.csdn.net/xyjawq1/article/details/74129316