溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Mybatis中怎么批量插入數(shù)據(jù)

發(fā)布時(shí)間:2021-06-22 17:07:58 來源:億速云 閱讀:296 作者:Leah 欄目:編程語(yǔ)言

本篇文章為大家展示了Mybatis中怎么批量插入數(shù)據(jù),內(nèi)容簡(jiǎn)明扼要并且容易理解,絕對(duì)能使你眼前一亮,通過這篇文章的詳細(xì)介紹希望你能有所收獲。

1. 循環(huán)插入

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);
}

測(cè)試代碼:

//java項(xiàng)目www.fhadmin.org
@SpringBootTest
class DemoApplicationTests {
	@Resource
	private StudentMapper studentMapper;

	@Test
	public void testInsert(){
		//數(shù)據(jù)生成
		List<Student> studentList = createData(100);

		//循環(huán)插入
		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標(biāo)簽

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>

  <!-- java項(xiàng)目www.fhadmin.org -->
  <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);
}

測(cè)試代碼:

//java項(xiàng)目www.fhadmin.org
@SpringBootTest
class DemoApplicationTests {
	@Resource
	private StudentMapper studentMapper;

	@Test
	public void testInsertByForeachTag(){
		//數(shù)據(jù)生成
		List<Student> studentList = createData(100);

		//使用foreach標(biāo)簽,拼接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. 批處理

測(cè)試代碼:

//java項(xiàng)目www.fhadmin.org
@SpringBootTest
class DemoApplicationTests {
	@Autowired
	private SqlSessionFactory sqlSessionFactory;

	@Test
	public void testInsertBatch(){
		//數(shù)據(jù)生成
		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;
	}
}
三種方式的對(duì)比

MySQL服務(wù)器版本: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>

三種插入方式在不同數(shù)據(jù)量下的表現(xiàn),測(cè)試結(jié)果:

插入方式10條100條500條1000條
循環(huán)插入496ms3330ms15584ms33755ms
foreach標(biāo)簽268ms366ms392ms684ms
批處理222ms244ms364ms426ms

三種方式中,批處理的方式效率是最高的,尤其是在數(shù)據(jù)量大的情況下尤為明顯。

其次是foreach標(biāo)簽,foreach標(biāo)簽是通過拼接SQL語(yǔ)句的方式完成批量操作的。但是當(dāng)拼接的SQL過多,導(dǎo)致SQL大小超過了MySQL服務(wù)器中max_allowed_packet變量的值時(shí),會(huì)導(dǎo)致操作失敗,拋出PacketTooBigException異常。

上述內(nèi)容就是Mybatis中怎么批量插入數(shù)據(jù),你們學(xué)到知識(shí)或技能了嗎?如果還想學(xué)到更多技能或者豐富自己的知識(shí)儲(chǔ)備,歡迎關(guān)注億速云行業(yè)資訊頻道。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI