微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

MyBatis的批量查询方法有哪些

这篇文章主要介绍了MyBatis的批量查询方法有哪些的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇MyBatis的批量查询方法有哪些文章都会有所收获,下面我们一起来看看吧。

一.直接循环插入

@RestController
@RequestMapping("/mybatis3/user")
@requiredArgsConstructor
public class UserController {

    private final IUserService iUserService;

    @GetMapping("/one")
    public Long one(){
       return iUserService.add();
    }
}

  Long add();

@Service
@requiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    private final UserMapper userMapper;

    @Override
    public Long add() {

        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");
        return (end-start);
    }
    }

 Integer insertUsers(User user);

 <insert id="insertUsers" >
        insert into user(username,password)
        values (#{username}, #{password})
    </insert>

最终耗时:14s多

MyBatis的批量查询方法有哪些

二.关闭MySql自动提交,手动进行循环插入提交

@RestController
@RequestMapping("/mybatis3/user")
@requiredArgsConstructor
public class UserController {

    private final IUserService iUserService;

        @GetMapping("/one")
    public Long one(){
       return iUserService.add();
    }
}

 Long add2();

@Service
@requiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    private final UserMapper userMapper;

//    手动开启sql的批量提交
    private final   sqlSessionTemplate sqlSessionTemplate;

    @Override
    public Long add2(){
        //关闭自动提交
        sqlSession sqlSession = sqlSessionTemplate.getsqlSessionFactory().openSession(ExecutorType.BATCH, false);
        UserMapper mapper = 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);
            mapper.insertUsers(user);
        }
        //自动提交sql
        sqlSession.commit();
        long end = System.currentTimeMillis();
        System.out.println("耗时:"+( end - start ) + "ms");
        return (end-start);
    }
    }

平均:0.12s

MyBatis的批量查询方法有哪些

第三种:用List集合的方式插入数据库(推荐)

@RestController
@RequestMapping("/mybatis3/user")
@requiredArgsConstructor
public class UserController {

    private final IUserService iUserService;

       @GetMapping("/one3")
    public Long one3(){
        return iUserService.add3();
    }
}

  Long add3();

@Service
@requiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    private final UserMapper userMapper;

  @Override
    public Long add3(){
        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.insertUsersThree(userList);
        long end = System.currentTimeMillis();
        System.out.println("耗时:"+( end - start ) + "ms");
        return (end-start);
    }
    }

 Integer insertUsersThree(List<User> userList);

<insert id="insertUsersThree">
        insert into user(username,password)
        values
        <foreach collection="userList" item="user" separator=",">
            (#{user.username},#{user.password})
        </foreach>
    </insert>

第四种: MyBatis-Plus提供的SaveBatch方法

@RestController
@RequestMapping("/mybatis3/user")
@requiredArgsConstructor
public class UserController {

    private final IUserService iUserService;

@GetMapping("/one4")
    public Long one4(){
        return iUserService.add4();
    }
}

  Long add4();

@Service
@requiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    private final UserMapper userMapper;

@Override
    public Long add4() {
        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");
        return (end-start);
    }
    }

直接报错:

MyBatis的批量查询方法有哪些

看报错信息:

长串:Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing Failed; nested exception is org.springframework.dao.DataIntegrityViolationException: com.huang.mybatis3.mapper.UserMapper.insert (batch index #1) Failed. Cause: java.sql.BatchUpdateException: Data truncation: Out of range value for column &lsquo;id&rsquo; at row 1
; Data truncation: Out of range value for column &lsquo;id&rsquo; at row 1; nested exception is java.sql.BatchUpdateException: Data truncation: Out of range value for column &lsquo;id&rsquo; at row 1] with root cause

短串:Data truncation: Out of range value for column &lsquo;id&rsquo; at row 1

翻译一下:

MyBatis的批量查询方法有哪些

可以发现就是我们的id超出范围:

MyBatis的批量查询方法有哪些

int类型改为bigint即可

故此我们可以得出一个结论:设置数据库id的时候设置为bigint还是蛮好的哈

平均时间:0.2s

MyBatis的批量查询方法有哪些

第五种 MyBatis-Plus提供的InsertBatchSomeColumn方法(推荐)

InsertBatchSomeColumn方法了解

MyBatis的批量查询方法有哪些

这个类的注解就写的很明白

扩展这个InsertBatchSomeColumn方法

@Slf4j
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));
        log.info("扩展的getmethodList方法被框架调用了");
        return methodList;
    }
}

扩展的方法注入bean容器

/**
 * @author Stone
 * @date 2023/1/3
 * @apiNote
 */
@Configuration
public class MybatisPlusConfig {
    @Bean
    public  EasysqlInjector sqlInjector(){
        return new EasysqlInjector();
    }
}

创建一个Mapper去实现我们的扩展的飞方法

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

业务层

@Override
    public Long add5() {
        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");
        return (end-start);
    }

耗时: 0.2 s

MyBatis的批量查询方法有哪些

关于“MyBatis的批量查询方法有哪些”这篇文章内容就介绍到这里,感谢各位的阅读!相信大家对“MyBatis的批量查询方法有哪些”知识都有一定的了解,大家如果还想学习更多知识,欢迎关注编程之家行业资讯频道。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐