赞
踩
项目中经常用到数据量较大的批量插入,然后使用mybatis的batch模式较频繁,故而写了个工具类 , 只需传入插入集合,插入方法,以及mapper即可使用 , 还是挺方便的, 后续如果有百万级数据量, 也可自行优化成多线程去插入 , 废话不多说, 咱么直接上代码 ;
package com.xwd.utils; import cn.hutool.core.thread.ThreadUtil; import com.baomidou.mybatisplus.core.conditions.Wrapper; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.baomidou.mybatisplus.core.toolkit.support.SFunction; import lombok.extern.slf4j.Slf4j; import org.apache.ibatis.session.ExecutorType; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.annotation.Order; import org.springframework.stereotype.Component; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; import java.util.function.ToIntBiFunction; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * @author xwd * @version 1.0 */ @Component @Order(5) @Slf4j public class MybatisUtil { @Autowired private SqlSessionFactory sqlSessionFactory; /** * * @param list 需要插入数据库的实体对象集合 * @param mapperClass mapper * @param mapperRToIntBiFunction 指定单条插入方法,必须是单条插入 */ public <T, Mapper> void batchInsert(List<T> list, Class<Mapper> mapperClass, ToIntBiFunction<Mapper, T> mapperRToIntBiFunction) { //切换batch模式 SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH); try { Mapper mapper = sqlSession.getMapper(mapperClass); for (T item : list) { //调用方法 mapperRToIntBiFunction.applyAsInt(mapper, item); } sqlSession.commit();//提交事务 } catch (Exception e) { log.error("批量插入报错", e); } finally { sqlSession.close(); } } }
下面给大家一个案例, 在service层注入, 使用即可 ;
完美插入,效率贼快,打完收工?
你以为人生的路这么简单? 那你还是太年轻了, 骚年,下面的话请务必牢记在心!!!
必须在配置数据库的时候,指定批量插入模式, 否则工具类就会在for循环中多次编译,然后多次调用IO,性能爆炸!!! 非常非常慢, 比你女朋友的大姨妈走的还慢. 各位小伙伴要小心哦!!!
&rewriteBatchedStatements=true #开启batch模式
以上就是今天的分享啦, 希望该工具类对各位小伙伴有帮助.
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。