如何使用MyBatis批量插入数据

 时间:2026-02-14 06:05:26

1、使用执行批量操作的sqlSession执行员工批量插入

package com.gwolf.crud.test;

import java.util.UUID;

import org.apache.ibatis.session.SqlSession;

import org.junit.Test;

import org.junit.runner.RunWith;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.test.context.ContextConfiguration;

import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.gwolf.crud.bean.Employee;

import com.gwolf.crud.dao.DepartmentMapper;

import com.gwolf.crud.dao.EmployeeMapper;

/**

 * 测试dao层的工作

 * @author CaoChuanPing

 *

 */

@RunWith(SpringJUnit4ClassRunner.class)

@ContextConfiguration(locations={"classpath:applicationContext.xml"})

public class MapperTest {

@Autowired

private DepartmentMapper departmentMapper;

@Autowired

private SqlSession sqlSession;

/**

* 测试DeptmentMapper

*/

@Test

public void testCRUD() {

EmployeeMapper mapper = sqlSession.getMapper(EmployeeMapper.class);

for(int i = 0 ;i < 10000;i++) {

mapper.insertSelective(new Employee(null,UUID.randomUUID().toString().substring(0, 5) + i,"M","gwolf_2010@126.com",1));

}

}

}

如何使用MyBatis批量插入数据

2、首先配置一个可以执行批量的sqlSession

<bean class="org.mybatis.spring.SqlSessionTemplate" id="sqlSession">

        <constructor-arg name="sqlSessionFactory" ref="sqlSessionFactoryBean" />

        <constructor-arg name="executorType" value="BATCH" />

</bean>

如何使用MyBatis批量插入数据

如何使用MyBatis批量插入数据

3、package com.gwolf.crud.test;

import org.apache.ibatis.session.SqlSession;

import org.junit.Test;

import org.junit.runner.RunWith;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.test.context.ContextConfiguration;

import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.gwolf.crud.dao.DepartmentMapper;

/**

 * 测试dao层的工作

 * @author CaoChuanPing

 *

 */

@RunWith(SpringJUnit4ClassRunner.class)

@ContextConfiguration(locations={"classpath:applicationContext.xml"})

public class MapperTest {

@Autowired

private DepartmentMapper departmentMapper;

@Autowired

private SqlSession sqlSession;

/**

* 测试DeptmentMapper

*/

@Test

public void testCRUD() {

    System.out.println(departmentMapper);

}

}

如何使用MyBatis批量插入数据

4、在测试方法中执行批量插入的方法。使用

@Test

public void testCRUD() {

      EmployeeMapper mapper = sqlSession.getMapper(EmployeeMapper.class);

      for(int i = 0 ;i < 10000;i++) {

         mapper.insertSelective(new Employee(null,UUID.randomUUID().toString().substring(0, 5) + i,"M","gwolf_2010@126.com",1));

    }

}

如何使用MyBatis批量插入数据

5、执行单元测试类:

如何使用MyBatis批量插入数据

6、在mysql中查看数据是否插入成功了。

如何使用MyBatis批量插入数据

  • 更新驱动程序:[20]SD卡
  • 系统重装后没有网卡驱动,如何安装驱动
  • win101909无法完成更新正在撤销解决方法
  • 如何给自己的电脑装虚拟机
  • win10怎么关闭secure boot
  • 热门搜索
    成都旅游景点地图 黑龙江省旅游局政务网 南京旅游景点介绍 诏安旅游景点大全 哈尔滨雪乡旅游 上海免费旅游景点大全 山东青岛旅游攻略 旅游科学 上海著名旅游景点 永州旅游景点大全