Mybatis三种批量插入数据的方式

 更新时间:2021年04月20日 09:49:14   作者:布禾  
这篇文章主要介绍了Mybatis的三种批量插入方式,帮助大家更好的理解和学习使用Java,感兴趣的朋友可以了解下

1. 循环插入

mapper.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.buhe.demo.mapper.StudentMapper">
  <insert id="insert" parameterType="Student">
    INSERT INTO tb_student (name, age, phone, address, class_id) VALUES (#{name},#{age},#{phone},#{address},#{classId})
  </insert>
</mapper>

mapper接口:

public interface StudentMapper {
    int insert(Student student);
}

测试代码:

@SpringBootTest
class DemoApplicationTests {
	@Resource
	private StudentMapper studentMapper;

	@Test
	public void testInsert(){
		//数据生成
		List<Student> studentList = createData(100);

		//循环插入
		long start = System.currentTimeMillis();
		studentList.stream().forEach(student -> studentMapper.insert(student));
		System.out.println(System.currentTimeMillis() - start);
	}

	private List<Student> createData(int size){
		List<Student> studentList = new ArrayList<>();
		Student student;
		for(int i = 0; i < size; i++){
			student = new Student();
			student.setName("小王" + i);
			student.setAge(18);
			student.setClassId(1);
			student.setPhone("1585xxxx669");
			student.setAddress("未知");
			studentList.add(student);
		}

		return studentList;
	}
}

2. foreach标签

mapper.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.buhe.demo.mapper.StudentMapper">
  <insert id="insert" parameterType="Student">
    INSERT INTO tb_student (name, age, phone, address, class_id) VALUES (#{name},#{age},#{phone},#{address},#{classId})
  </insert>

  <insert id="insertBatch">
    INSERT INTO tb_student (name, age, phone, address, class_id) VALUES
    <foreach collection="list" separator="," item="item">
        (#{item.name},#{item.age},#{item.phone},#{item.address},#{item.classId})
    </foreach>
  </insert>
</mapper>

mapper接口:

public interface StudentMapper {
    int insert(Student student);

    int insertBatch(List<Student> studentList);
}

测试代码:

@SpringBootTest
class DemoApplicationTests {
	@Resource
	private StudentMapper studentMapper;

	@Test
	public void testInsertByForeachTag(){
		//数据生成
		List<Student> studentList = createData(100);

		//使用foreach标签,拼接SQL插入
		long start = System.currentTimeMillis();
		studentMapper.insertBatch(studentList);
		System.out.println(System.currentTimeMillis() - start);
	}


	private List<Student> createData(int size){
		List<Student> studentList = new ArrayList<>();
		Student student;
		for(int i = 0; i < size; i++){
			student = new Student();
			student.setName("小王" + i);
			student.setAge(18);
			student.setClassId(1);
			student.setPhone("1585xxxx669");
			student.setAddress("未知");
			studentList.add(student);
		}

		return studentList;
	}
}

3. 批处理

测试代码:

@SpringBootTest
class DemoApplicationTests {
	@Autowired
	private SqlSessionFactory sqlSessionFactory;

	@Test
	public void testInsertBatch(){
		//数据生成
		List<Student> studentList = createData(100);

                //使用批处理
		long start = System.currentTimeMillis();
		SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH,false);
		StudentMapper studentMapperNew = sqlSession.getMapper(StudentMapper.class);
		studentList.stream().forEach(student -> studentMapperNew.insert(student));
		sqlSession.commit();
		sqlSession.clearCache();
		System.out.println(System.currentTimeMillis() - start);
	}

	private List<Student> createData(int size){
		List<Student> studentList = new ArrayList<>();
		Student student;
		for(int i = 0; i < size; i++){
			student = new Student();
			student.setName("小王" + i);
			student.setAge(18);
			student.setClassId(1);
			student.setPhone("1585xxxx669");
			student.setAddress("未知");
			studentList.add(student);
		}

		return studentList;
	}
}

三种方式的对比

MySQL服务器版本:5.6.4

其他依赖版本如下:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.4.4</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.buhe</groupId>
	<artifactId>demo</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>demo</name>
	<description>Demo project for Spring Boot</description>
	<properties>
		<java.version>1.8</java.version>
	</properties>
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>

		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.41</version>
		</dependency>
		<dependency>
			<groupId>org.mybatis.spring.boot</groupId>
			<artifactId>mybatis-spring-boot-starter</artifactId>
			<version>1.3.1</version>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>

		<resources>
			<resource>
				<directory>src/main/java</directory>
				<includes>
					<include>**/*.xml</include>
				</includes>
			</resource>
		</resources>
	</build>

</project>

三种插入方式在不同数据量下的表现,测试结果:

插入方式 10条 100条 500条 1000条
循环插入 496ms 3330ms 15584ms 33755ms
foreach标签 268ms 366ms 392ms 684ms
批处理 222ms 244ms 364ms 426ms

三种方式中,批处理的方式效率是最高的,尤其是在数据量大的情况下尤为明显。

其次是foreach标签,foreach标签是通过拼接SQL语句的方式完成批量操作的。但是当拼接的SQL过多,导致SQL大小超过了MySQL服务器中max_allowed_packet变量的值时,会导致操作失败,抛出PacketTooBigException异常。

最后是循环插入的方式,这种方式在数据量小的时候可以使用,在数据量大的情况下效率要低很多。

以上就是Mybatis的三种批量插入方式的详细内容,更多关于Mybatis 批量插入的资料请关注脚本之家其它相关文章!

相关文章

  • 使用java代码代替xml实现SSM教程

    使用java代码代替xml实现SSM教程

    这篇文章主要介绍了使用java代码代替xml实现SSM教程,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-12-12
  • mybatis中使用oracle关键字出错的解决方法

    mybatis中使用oracle关键字出错的解决方法

    这篇文章主要给大家介绍了关于mybatis中使用oracle关键字出错的解决方法,文中通过示例代码将解决的方法介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面来一起看看吧。
    2017-08-08
  • spring如何使用命名空间p简化bean的配置

    spring如何使用命名空间p简化bean的配置

    这篇文章主要介绍了spring如何使用命名空间p简化bean的配置,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-01-01
  • Spring与bean有关的生命周期示例详解

    Spring与bean有关的生命周期示例详解

    这篇文章主要给大家介绍了关于Spring与bean有关的生命周期的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者使用Spring具有一定的参考学习价值,需要的朋友们下面来一起学习学习吧
    2020-07-07
  • spring @profile注解的使用方法

    spring @profile注解的使用方法

    本篇文章主要介绍了spring @profile注解的使用方法,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-10-10
  • Java实现post请求详细代码(带有参数)

    Java实现post请求详细代码(带有参数)

    这篇文章主要给大家介绍了关于Java实现带有参数post请求的相关资料,文中通过代码示例介绍的非常详细,对大家学习或者使用Java具有一定的参考学习价值,需要的朋友可以参考下
    2023-08-08
  • SpringBoot指定激活配置文件的方法

    SpringBoot指定激活配置文件的方法

    Spring Boot 对多环境整合已经有了很好的支持,能够在运行间、打包时自由切换环境,这篇文章主要介绍了SpringBoot指定激活配置文件,需要的朋友可以参考下
    2023-11-11
  • java判断请求是来自PC端还是手机端小技巧

    java判断请求是来自PC端还是手机端小技巧

    这篇文章主要为大家介绍了java判断请求是来自PC端还是手机端小技巧,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2023-06-06
  • SpringBoot+MDC实现链路调用日志的方法

    SpringBoot+MDC实现链路调用日志的方法

    MDC是 log4j 、logback及log4j2 提供的一种方便在多线程条件下记录日志的功能,这篇文章主要介绍了SpringBoot+MDC实现链路调用日志,需要的朋友可以参考下
    2022-12-12
  • JAVAEE model1模型实现商品浏览记录(去除重复的浏览记录)(一)

    JAVAEE model1模型实现商品浏览记录(去除重复的浏览记录)(一)

    这篇文章主要为大家详细介绍了JAVAEE model1模型实现商品浏览记录,去除重复的浏览记录,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2016-11-11

最新评论