Mybatis批量插入的三种实现方法

 更新时间:2023年10月30日 09:23:58   作者:秋官  
在日常开发中,如果要操作数据库的话,或多或少都会遇到批量数据的处理,本文主要介绍了Mybatis批量插入的三种实现方法,感兴趣的可以了解一下

在日常开发中,如果要操作数据库的话,或多或少都会遇到批量数据的处理,我们公司使用的mybaits-plus作为持久层的框架,今天就简单介绍一下mybaits批量操作数据库的几种方式。

1.循环插入

其实这种方式并不是批量插入,只是在日常开发中,使用这种方式的还是比较多的。

@RunWith(SpringRunner.class)
@SpringBootTest
public class BatchTest {

    @Resource
    private StudentMapper studentMapper;


    @Test
    public void test(){
        List<Student> students = generateStudentData(100);

        long start = System.currentTimeMillis();
        students.forEach(studentMapper::insert);
        System.out.println("循环插入: " + students.size() + " 条数据,共计耗时:" + (System.currentTimeMillis() - start) + " 毫秒");
    }


    public static List<Student> generateStudentData(int size){
        List<Student> list = new ArrayList<>(size);
        Random random = new Random();
        for (int i = 0; i < size; i++) {
            Student student = new Student();
            student.setName("zhangsan-" + i);
            student.setAge(random.nextInt(40));
            student.setPhone("15077828899");
            student.setBirthday(LocalDateTime.now());

            list.add(student);
        }

        return list;
    }
}

2.foreach方式插入

@RunWith(SpringRunner.class)
@SpringBootTest
public class BatchTest {

    @Resource
    private StudentMapper studentMapper;


    @Test
    public void test3(){
        List<Student> students = generateStudentData(100);

        long foreachStart = System.currentTimeMillis();
        studentMapper.insertBatch(students);
        System.out.println("foreach插入: " + students.size() + " 条数据,共计耗时:" + (System.currentTimeMillis() - foreachStart) + " 毫秒");
    }


    public static List<Student> generateStudentData(int size){
        List<Student> list = new ArrayList<>(size);
        Random random = new Random();
        for (int i = 0; i < size; i++) {
            Student student = new Student();
            student.setName("zhangsan-" + i);
            student.setAge(random.nextInt(40));
            student.setPhone("15077828899");
            student.setBirthday(LocalDateTime.now());

            list.add(student);
        }

        return list;
    }
}

StudentMapper 接口如下:

public interface StudentMapper extends BaseMapper<Student> {

    /**
     * 批量插入
     */
    int insertBatch(@Param("entities") List<Student> entities);

    /**
     * 批量更新或者插入
     */
    int insertOrUpdateBatch(@Param("entities") List<Student> entities);

}

StudentMapper.xml内容如下:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.efreight.oss.transfer.dao.StudentMapper">

    <resultMap type="com.efreight.oss.transfer.entity.Student" id="StudentMap">
        <result property="id" column="id" jdbcType="INTEGER"/>
        <result property="name" column="name" jdbcType="VARCHAR"/>
        <result property="age" column="age" jdbcType="INTEGER"/>
        <result property="birthday" column="birthday" jdbcType="TIMESTAMP"/>
        <result property="phone" column="phone" jdbcType="VARCHAR"/>
    </resultMap>

    <!-- 批量插入 -->
    <insert id="insertBatch" keyProperty="id" useGeneratedKeys="true">
        insert into cargo.student(name, age, birthday, phone)
        values
        <foreach collection="entities" item="entity" separator=",">
        (#{entity.name}, #{entity.age}, #{entity.birthday}, #{entity.phone})
        </foreach>
    </insert>

    <!-- 批量插入或按主键更新 -->
    <insert id="insertOrUpdateBatch" keyProperty="id" useGeneratedKeys="true">
        insert into cargo.student(name, age, birthday, phone)
        values
        <foreach collection="entities" item="entity" separator=",">
            (#{entity.name}, #{entity.age}, #{entity.birthday}, #{entity.phone})
        </foreach>
        on duplicate key update
        name = values(name) , age = values(age) , birthday = values(birthday) , phone = values(phone)
    </insert>

</mapper>

搭配 useGeneratedKeys="true" 和 keyProperty="id" 属性(这个id是javaBean的属性),可以获取自增主键,有时候这个主键我们是非常需要的。

3.批处理方式插入

通过 ExecutorType.BATCH来构建一个可以完成批处理工作的执行器

@RunWith(SpringRunner.class)
@SpringBootTest
public class BatchTest {

    @Resource
    private StudentMapper studentMapper;

    @Resource
    private SqlSessionTemplate sqlSessionTemplate;


    @Test
    public void test2(){
        List<Student> students = generateStudentData(100);

        long batchStart = System.currentTimeMillis();
        try(SqlSession sqlSession = this.sqlSessionTemplate.getSqlSessionFactory().openSession(ExecutorType.BATCH, false)) {
            StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
            for (int i = 0; i < students.size(); i++) {  
                studentMapper.insert(students.get(i));  
                if (i % 1000 == 0 || i == students.size() - 1) {  
                sqlSession.flushStatements();  
                }  
            }  
            sqlSession.commit();
        }
        System.out.println("mybatis批处理插入: " + students.size() + " 条数据,共计耗时:" + (System.currentTimeMillis() - batchStart) + " 毫秒");
    }


    public static List<Student> generateStudentData(int size){
        List<Student> list = new ArrayList<>(size);
        Random random = new Random();
        for (int i = 0; i < size; i++) {
            Student student = new Student();
            student.setName("zhangsan-" + i);
            student.setAge(random.nextInt(40));
            student.setPhone("15077828899");
            student.setBirthday(LocalDateTime.now());

            list.add(student);
        }

        return list;
    }
}

注意:批处理方式是无法获取自增主键的。

顺便说一下,现在使用mybatis-plus的也非常多,他也提供了批量插入的功能,它内部使用的就是ExecutorType.BATCH 来构建的。

关于三者性能的比较大家可以跑下看看,循环插入的方式性能最差,能不用就尽量不用,在foreach和批处理中,我测试发现foreach的性能最好(我用的MySQL是5.7),所以项目中我们批处理使用的都是foreach, 因为一般我们一般批量插入最多也就2000条左右的数据,但是大家可以根据自己机器的实际情况,去跑一下看看。

插入方式100条1000条10000条10万条
循环插入1599 毫秒14336 毫秒140793 毫秒*
foreach62 毫秒364 毫秒3249 毫秒23940 毫秒
批处理321 毫秒6868 毫秒72851 毫秒457005 毫秒

到此这篇关于Mybatis批量插入的三种实现方法的文章就介绍到这了,更多相关Mybatis批量插入 内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • Spring5学习之基础知识总结

    Spring5学习之基础知识总结

    这篇文章主要介绍了Spring5学习之基础知识总结,文中有非常详细的代码示例,对正在学习java的小伙伴们有非常好的帮助,需要的朋友可以参考下
    2021-05-05
  • Spring实战之设置普通属性值的方法示例

    Spring实战之设置普通属性值的方法示例

    这篇文章主要介绍了Spring实战之设置普通属性值的方法,结合实例形式分析了Spring设置普通属性值的方法及相关操作注意事项,需要的朋友可以参考下
    2019-11-11
  • java中unicode和中文相互转换的简单实现

    java中unicode和中文相互转换的简单实现

    下面小编就为大家带来一篇java中unicode和中文相互转换的简单实现。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2016-08-08
  • SptingBoot过滤器Filter的使用详解

    SptingBoot过滤器Filter的使用详解

    这篇文章主要介绍了SptingBoot过滤器Filter的使用详解,Filter属于Servlet规范,并不是Spring独有的,Filter主要用于拦截请求,做一些业务逻辑操作,然后可以决定请求是否可以继续往下分发,落到其他的Filter或者对应的Servlet,需要的朋友可以参考下
    2023-09-09
  • 基于Spring Cloud Zookeeper实现服务注册与发现

    基于Spring Cloud Zookeeper实现服务注册与发现

    这篇文章主要介绍了基于Spring Cloud Zookeeper实现服务注册与发现,帮助大家更好的理解和学习spring框架,感兴趣的朋友可以了解下
    2020-11-11
  • 一文详解Java如何创建和销毁对象

    一文详解Java如何创建和销毁对象

    Java由Sun Microsystems发明并在1995年发布,是世界上使用最广泛的编程语言之一。本文主要和大家介绍一下Java是如何创建和销毁对象的,希望对大家有所帮助
    2022-11-11
  • 快速解决commons-fileupload组件无法处理自定义head信息的bug

    快速解决commons-fileupload组件无法处理自定义head信息的bug

    问题在于fileupload组件解析完自定义的head节点后,却忘记传递到FileItemStreamImpl中了,稍作修订,即可修正该bug
    2013-08-08
  • 浅谈Java中的class类

    浅谈Java中的class类

    这篇文章主要介绍了浅谈Java中的class类,具有一定借鉴价值,需要的朋友可以参考下
    2018-01-01
  • 浅谈Java的WeakHashMap源码

    浅谈Java的WeakHashMap源码

    这篇文章主要介绍了浅谈Java的WeakHashMap源码,WeakHashMap,从名字可以看出它是某种 Map,它的特殊之处在于 WeakHashMap 里的entry可能会被GC自动删除,即使程序员没有调用remove()或者clear()方法,需要的朋友可以参考下
    2023-09-09
  • Easypoi 轻松实现复杂excel文件导出功能

    Easypoi 轻松实现复杂excel文件导出功能

    这篇文章主要介绍了Easypoi 轻松实现复杂excel文件导出功能,本文通过示例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2021-11-11

最新评论