java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > MyBatis批量插入

MyBatis批量插入的五种方式小结(MyBatis以集合方式批量新增)

作者:小徐敲java

本文主要介绍了MyBatis批量插入的五种方式小结(MyBatis以集合方式批量新增),文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

一、准备工作

1.1、导入pom.xml依赖

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <scope>runtime</scope>
</dependency>

<!--Mybatis依赖-->
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.2.2</version>
</dependency>

<!--Mybatis-Plus依赖-->
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>3.5.2</version>
</dependency>

<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <optional>true</optional>
</dependency>

1.2、配置yml文件

server:
  port: 8080
 
spring:
  datasource:
    username: root
    password: root
    url: jdbc:mysql://localhost:3306/user?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=UTC
    driver-class-name: com.mysql.cj.jdbc.Driver
 
mybatis:
  mapper-locations: classpath:mapping/*.xml

1.3、公用的User类

@Data
public class User {
 
    private int id;
    private String username;
    private String password;
}

二、MyBatis利用For循环批量插入

2.1、编写UserService服务类,测试一万条数据耗时情况

@Service
public class UserService {
 
    @Resource
    private UserMapper userMapper;
 
    public void InsertUsers(){
        long start = System.currentTimeMillis();
        for(int i = 0 ;i < 10000; i++) {
            User user = new User();
            user.setUsername("name" + i);
            user.setPassword("password" + i);
            userMapper.insertUsers(user);
        }
        long end = System.currentTimeMillis();
        System.out.println("一万条数据总耗时:" + (end-start) + "ms" );
    }
 
}

2.2、编写UserMapper接口

@Mapper
public interface UserMapper {
 
    Integer insertUsers(User user);
}

2.3、编写UserMapper.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.ithuang.demo.mapper.UserMapper">
    <insert id="insertUsers">
        INSERT INTO user (username, password)
        VALUES(#{username}, #{password})
    </insert>
</mapper>

2.4、进行单元测试

@SpringBootTest
class DemoApplicationTests {
 
    @Resource
    private UserService userService;
 
    @Test
    public void insert(){
        userService.InsertUsers();
    }
 
}

2.5、结果输出

一万条数据总耗时:26348ms

三、MyBatis的手动批量提交

3.1、其他保持不变,Service层作稍微的变化

@Service
public class UserService {
 
    @Resource
    private UserMapper userMapper;
 
    @Resource
    private SqlSessionTemplate sqlSessionTemplate;
 
    public void InsertUsers(){
        //关闭自动提交
        SqlSession sqlSession = sqlSessionTemplate.getSqlSessionFactory().openSession(ExecutorType.BATCH, false);
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        long start = System.currentTimeMillis();
        for(int i = 0 ;i < 10000; i++) {
            User user = new User();
            user.setUsername("name" + i);
            user.setPassword("password" + i);
            userMapper.insertUsers(user);
        }
        sqlSession.commit();
        long end = System.currentTimeMillis();
        System.out.println("一万条数据总耗时:" + (end-start) + "ms" );
    }
 
}

3.2、结果输出

一万条数据总耗时:24516ms

四、MyBatis以集合方式批量新增(推荐)

4.1、编写UserService服务类

@Service
public class UserService {
 
    @Resource
    private UserMapper userMapper;
 
    public void InsertUsers(){
        long start = System.currentTimeMillis();
        List<User> userList = new ArrayList<>();
        User user;
        for(int i = 0 ;i < 10000; i++) {
            user = new User();
            user.setUsername("name" + i);
            user.setPassword("password" + i);
            userList.add(user);
        }
        userMapper.insertUsers(userList);
        long end = System.currentTimeMillis();
        System.out.println("一万条数据总耗时:" + (end-start) + "ms" );
    }
 
}

4.2、编写UserMapper接口

@Mapper
public interface UserMapper {
 
    Integer insertUsers(List<User> userList);
}

4.3、编写UserMapper.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.ithuang.demo.mapper.UserMapper">
    <insert id="insertUsers">
        INSERT INTO user (username, password)
        VALUES
        <foreach collection ="userList" item="user" separator =",">
            (#{user.username}, #{user.password})
        </foreach>
    </insert>
</mapper>

4.4、输出结果

一万条数据总耗时:521ms

五、MyBatis-Plus提供的SaveBatch方法

5.1、编写UserService服务

@Service
public class UserService extends ServiceImpl<UserMapper, User> implements IService<User> {
 
    public void InsertUsers(){
        long start = System.currentTimeMillis();
        List<User> userList = new ArrayList<>();
        User user;
        for(int i = 0 ;i < 10000; i++) {
            user = new User();
            user.setUsername("name" + i);
            user.setPassword("password" + i);
            userList.add(user);
        }
        saveBatch(userList);
        long end = System.currentTimeMillis();
        System.out.println("一万条数据总耗时:" + (end-start) + "ms" );
    }
}

5.2、编写UserMapper接口

@Mapper
public interface UserMapper extends BaseMapper<User> {
 
}

5.3、单元测试结果

一万条数据总耗时:24674ms

六、MyBatis-Plus提供的InsertBatchSomeColumn方法(推荐)

6.1、编写EasySqlInjector 自定义类

public class EasySqlInjector extends DefaultSqlInjector {
 
    @Override
    public List<AbstractMethod> getMethodList(Class<?> mapperClass, TableInfo tableInfo) {
        // 注意:此SQL注入器继承了DefaultSqlInjector(默认注入器),调用了DefaultSqlInjector的getMethodList方法,保留了mybatis-plus的自带方法
        List<AbstractMethod> methodList = super.getMethodList(mapperClass, tableInfo);
        methodList.add(new InsertBatchSomeColumn(i -> i.getFieldFill() != FieldFill.UPDATE));
        return methodList;
    }
 
}

6.2、定义核心配置类注入此Bean

@Configuration
public class MybatisPlusConfig {
 
    @Bean
    public EasySqlInjector sqlInjector() {
        return new EasySqlInjector();
    }
}

6.3、编写UserService服务类

public class UserService{
 
    @Resource
    private UserMapper userMapper;
    public void InsertUsers(){
        long start = System.currentTimeMillis();
        List<User> userList = new ArrayList<>();
        User user;
        for(int i = 0 ;i < 10000; i++) {
            user = new User();
            user.setUsername("name" + i);
            user.setPassword("password" + i);
            userList.add(user);
        }
        userMapper.insertBatchSomeColumn(userList);
        long end = System.currentTimeMillis();
        System.out.println("一万条数据总耗时:" + (end-start) + "ms" );
    }
}

6.4、编写EasyBaseMapper接口

public interface EasyBaseMapper<T> extends BaseMapper<T> {
    /**
     * 批量插入 仅适用于mysql
     *
     * @param entityList 实体列表
     * @return 影响行数
     */
    Integer insertBatchSomeColumn(Collection<T> entityList);
}

6.5、编写UserMapper接口

@Mapper
public interface UserMapper<T> extends EasyBaseMapper<User> {
    
}

6.6、单元测试结果

一万条数据总耗时:575ms

到此这篇关于MyBatis批量插入的五种方式小结(MyBatis以集合方式批量新增)的文章就介绍到这了,更多相关MyBatis批量插入内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文