MyBatis批量更新(updateBatch)
更新多条数据,每条数据都不一样
通常有两种解决方法:
1) 在业务代码中循环遍历逐条更新。
2) 一次性更新所有数据(更准确的说是一条sql语句来更新所有数据,逐条更新的操作放到数据库端,在业务代码端展现的就是一次性更新所有数据)。
逐条更新(java实现)
updateBatch(List<MyData> datas){for(MyData data : datas){try{myDataDao.update(data);//更新一条数据,mybatis中如下面的xml文件的update}catch(Exception e){...//如果更新失败可以做一些其他的操作,比如说打印出错日志等}}
}//mybatis中update操作的实现
<update>update mydataset ...where ...
</update>
这种方式最大的问题就是效率问题,逐条更新,每次都会连接数据库,然后更新,再释放连接资源(虽然通过连接池可以将频繁连接数据的效率大大提高,抗不住数据量大),这中损耗在数据量较大的时候便会体现出效率问题。这也是在满足业务需求的时候,通常会使用上述提到的第二种批量更新的实现
逐条更新(mybatis实现)
通过(foreach标签实现)
要实现批量更新,首先得设置mysql支持批量操作,在jdbc链接中需要附加&allowMultiQueries=true属性才行
jdbc:mysql://localhost:3306/dbname?characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true
<update id="updateBatch" parameterType="java.util.List"> <foreach collection="list" item="item" index="index" open="" close="" separator=";">update course<set>name=${item.name}</set>where id = ${item.id}</foreach>
</update>
foreach 元素的属性主要有 item,index,open,separator,close,collection。
属性 | 描述 |
---|---|
collection | 表示迭代集合的名称,可以使用@Param注解指定, 该参数为必选 |
item | 表示本次迭代获取的元素,若collection为List、Set或者数组,则表示其中的元素;若collection为map,则代表key-value的value,该参数为必选 |
open | 表示该语句以什么开始,最常用的是左括弧’(’,注意:mybatis会将该字符拼接到整体的sql语句之前,并且只拼接一次,该参数为可选项 |
close | 表示该语句以什么结束,最常用的是右括弧’)’,注意:mybatis会将该字符拼接到整体的sql语句之后,该参数为可选项 |
separator | mybatis会在每次迭代后给sql语句append上separator属性指定的字符,该参数为可选项 |
index | 在list、Set和数组中,index表示当前迭代的位置,在map中,index代指是元素的key,该参数是可选项。 |
sql批量更新
原始sql 批量更新语句
update mydata_table set status = casewhen id = #{item.id} then #{item.status}//此处应该是<foreach>展开值...endwhere id in (...);
整体mybatis 批量更新脚本
<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"><if test="item.status !=null and item.status != -1">when id=#{item.id} then #{item.status}</if><if test="item.status == null or item.status == -1">when id=#{item.id} then mydata_table.status//原数据</if></foreach></trim></trim>where id in<foreach collection="list" index="index" item="item" separator="," open="(" close=")">#{item.id,jdbcType=BIGINT}</foreach>
</update>
参考链接
https://www.cnblogs.com/eternityz/p/12284760.html