在项目中我们需要一次更新多条数据,有两种方式:
- 在业务代码汇总循环遍历逐条更新。
- 一次性更新所有数据(一条sql语句来更新所有数据,逐条更新操作放到数据库端,在业务代码展现的就是一次更新所有数据)
1、逐条更新
逐条更新比较简单,不易出错,但是效率比较低下,我们主要介绍第二种方法。
2、批量更新
- 一种用for循环通过循环传过来的参数集合,循环出N条sql
- 另一种用mysql的case when 条件判断变相的进行批量更新
注意第一种方法要想成功,需要在db链接url后面带一个参数 &allowMultiQueries=true
即: jdbc:mysql://localhost:3306/mysqlTest?characterEncoding=utf-8&allowMultiQueries=true
<!-- 批量更新第一种方法,通过接收传进来的参数list进行循环着组装sql --> <update id="batchUpdate" parameterType="java.util.Map"> <!-- 接收list参数,循环着组装sql语句,注意for循环的写法 separator=";" 代表着每次循环完,在sql后面放一个分号 item="cus" 循环List的每条的结果集 collection="list" list 即为 map传过来的参数key --> <foreach collection="list" separator=";" item="cus"> update t_customer set c_name = #{cus.name}, c_age = #{cus.age}, c_sex = #{cus.sex}, c_ceroNo = #{cus.ceroNo}, c_ceroType = #{cus.ceroType} where id = #{cus.id} </foreach> </update>
第二种写法:
<update id="updateBatch" parameterType="java.util.List"> update mydata_table set status= <foreach collection="list" item="item" index="index" separator=" " open="case ID" close="end"> when #{item.id} then #{item.status} </foreach> where id in <foreach collection="list" index="index" item="item" separator="," open="(" close=")"> #{item.id,jdbcType=BIGINT} </foreach> </update>
其中when...then...是sql中的"switch" 语法。这里借助mybatis的<foreach>语法来拼凑成了批量更新的sql,上面的意思就是批量更新id在updateBatch参数所传递List中的数据的status字段。还可以使用<trim>实现同样的功能,代码如下:
<update id="updateBatch" parameterType="java.util.List"> update mydata_table <trim prefix="set" suffixOverrides=","> <trim prefix="status =case" suffix="end,"> <foreach collection="list" item="item" index="index"> when id=#{item.id} then #{item.status} </foreach> </trim> </trim> where id in <foreach collection="list" index="index" item="item" separator="," open="(" close=")"> #{item.id,jdbcType=BIGINT} </foreach> </update>
参考: