//MySQL 批量更新的方法
public void uptBatch(List<YourBean> beanList) {
//批量更新的操作
if (null != beanList && beanList.size() > 0) {
// 每个批次条数 100 ,分批条数不能太大,防止sql过长导致更新失败的异常
Integer partSize = Integer.parseInt(pSize);
Integer size = beanList.size();
// 判断是否有必要分批
if (partSize < size) {
// 批次数
int part = size / partSize;
System.out.println("共有 : " + size + "条,!" + " 分为 :" + part + "批");
for (int i = 0; i < part; i++) {
// partSize 条
List<YourBean> subList = beanList.subList(0, partSize);
yourDao.batchUpdate(subList);
// 剔除
beanList.subList(0, partSize).clear();
}
if (!beanList.isEmpty()) {
// 表示整除后的剩余项
yourDao.batchUpdate(beanList);
}
} else {
yourDao.batchUpdate(beanList);
}
}
}
<update id="batchUpdate" parameterType="java.util.List">
update t_yourtable
<set>
column1 =
<foreach collection="list" item="item" index="index" separator=" " open="case id" close="end">
when #{item.id} then #{item.name1}
</foreach>
,column2 =
<foreach collection="list" item="item" index="index" separator=" " open="case id" close="end">
when #{item.id} then #{item.name2}
</foreach>
</set>
<where>
<choose>
<when test="list != null and list.size() >0">
id in
<foreach item="item" index="index" collection="list" open="(" separator="," close=")">
#{item.id}
</foreach>
</when>
<otherwise>
id = ''
</otherwise>
</choose>
</where>
</update>
//为了不影响原集合,可以新开辟集合去接收oldList
List<YourBean> listNew = new ArrayList<>();
listNew.addAll(listOld.subList(0, listOld.size() - 1));
<insert id="insertBatch" parameterType="java.util.List">
insert into your_table
(id,
name,
status)
values
<foreach collection="list" item="list" separator=",">
( #{list.id},
#{list.name},
#{list.status})
</foreach>
</insert>