Java8 实现批量插入和更新,SpringBoot实现批量插入和更新,Mybatis实现批量插入和更新

前言

基于mybatis实现的批量插入和更新

由于直接执行批量所有数据可能会出现长度超出报错问题,使用如下方式即可解决

实现

原理还是分配执行,这里的100就是设定每次执行最大数

java 复制代码
	/**
	 * 封装使用批量添加或修改数据库操作
	 * 
	 * @param list 集合
	 * @param insertFunc 需要执行的任务 (Consumer lambda表达式方法引用的任务目标)
	 * @param <T> 自定义类型
	 */
	public static <T> void insertBatch(List<T> list, Consumer<List<T>> consumer, boolean asyn) {
		int max = 100; // 每次批量限制数
		if (list.size() > max) {
			List<List<T>> allList = new ArrayList<>();
			List<T> tempList = new ArrayList<>();
			for (int i = 0; i < list.size(); i++) {
				tempList.add(list.get(i));
				if ((i % max) == 0) {
					allList.add(tempList);
					tempList = new ArrayList<>();
				}
			}
			if (tempList.size() > 0) {
				allList.add(tempList);
			}
			if(asyn) {
				// 多线程遍历(异步)-这里直接遍历无需accept(接口式方法简化)
				allList.parallelStream().forEach(consumer);
			}else {
				// 多线程遍历(同步)-这里直接遍历无需accept(接口式方法简化)
				allList.forEach(consumer);
			}
		} else {
			// 执行泛型集合数据
			consumer.accept(list);
		}
	}

使用

xml

这里使用插入作为例子,也可以使用批量更新

xml 复制代码
	<insert id="insertBatchUser">
        insert into sys_user(
        	name,
        	sex
        )values 
        <foreach collection="list" item="item" index="index" separator=",">
	        (#{item.name}, #{item.sex})
	    </foreach>
    </insert>

更新的写法

xml 复制代码
    <update id="updateBatchUser">
        <foreach collection="list" item="item" index="index" separator=";">
            update sys_user
            <set>
                <if test="item.name != null and item.name != ''">
                    name = #{item.name},
                </if>
                update_date = #{item.updateDate}
                <where>
                    id = #{item.id}
                </where>
            </set>
        </foreach>
    </update>

批量数据

java 复制代码
	List<UserBean> list = new ArrayList<>();
	UserBean user1 = new UserBean();
	user1.setName("张三");
	user1.setSex("男");
	UserBean user2 = new UserBean();
	user2.setName("李四");
	user2.setSex("男");
	list.add(user1);
	list.add(user2);

调用

java 复制代码
	// 执行批量插入或修改
	Consumer<List<UserBean>> consumer = v -> dao.insertBatchUser(v);
	insertBatch(list, consumer, true)
相关推荐
程序员阿明13 分钟前
spring boot 4 + netty搭建JT808车载终端服务
spring boot·后端
飞花漫卷,情随岁迁31 分钟前
命令进阶与 Playbook 快速入门
java·linux·运维·服务器·网络·数据库·智能路由器
hookserver34 分钟前
企业微信 iPad 协议全功能接入效果实测
java·http·微信·企业微信·ipad
IT枫斗者35 分钟前
缓存和数据库一致性:先更库还是先删缓存,延迟双删怎么落地
java·开发语言·数据库·人工智能·缓存·gateway
AI开源软件42 分钟前
SpringBoot多系统同步:别让“同名数据”变成“同一条数据”
vue.js·spring boot·企业管理·mdm
播播资源44 分钟前
MiniMax-M4 API 选型指南:接入、思考参数与缓存避坑(含实测数据)
java·spring·缓存
软件技术NINI1 小时前
基于 SpringBoot 的共享植物管理系统
java·spring boot·后端
海宇数据1 小时前
零信任架构实战:基于海宇企业司法涉诉构建自动化合同法务审查网关
java·人工智能·架构·自动化
IT研究室1 小时前
最新计算机毕业设计选题推荐-基于spring boot的家政保洁预约系统-网站-文档指导-Java-springboot
java·spring boot·课程设计
FYKJ_20101 小时前
springboot网上汽车租赁系统93523-计算机毕业设计、课程设计
java·vue.js·spring boot·后端·python·汽车·课程设计