mybatis 扩展 批量插入

mybatis 扩展 批量插入

场景

mybatis plus 中有批量插入的方法 saveBatch, 不过这个最后 还是循环遍历插入,其实还有其他方式, 给 BaseMapper中增加另一个批量插入的方法 insertBatchSomeColumn, 其实 mybatis plus 早就 实现了,只不过没有在 BaseMapper中加入

InsertBatchSomeColumn实现

就是拼接成如 insert into table (c1,c2) values(v1,v2),(v11,v22) 这种SQL

ExtBaseMapper

自定义 ExtBaseMapper

java 复制代码
public interface ExtBaseMapper<T> extends BaseMapper<T> {

    /**
     * 批量插入: insertBatchSomeColumn 名称和 InsertBatchSomeColumn 中 getMethod 方法相同
     * @param list
     */
    void insertBatchSomeColumn(@Param("list") List<T> list);
}

重写 DefaultSqlInjector

java 复制代码
public class ExtSqlInjector extends DefaultSqlInjector {
    @Override
    public List<AbstractMethod> getMethodList(Class<?> mapperClass) {
        List<AbstractMethod> methodList = super.getMethodList(mapperClass);
        methodList.add(new InsertBatchSomeColumn());
        return methodList;
    }
}

依赖注入

java 复制代码
@Bean
public ExtSqlInjector extSqlInjector(){
    return new ExtSqlInjector();
}

注意,把 ExtBaseMapper 放在 mapperscan 包下

java 复制代码
public interface UserMapper extends ExtBaseMapper<ReservationDeviceConfigModel> {
}

测试

java 复制代码
public void addBatch() {
    List<UserModel> list = new ArrayList<>();
    for (int i = 0; i < 2; i++) {
        UserModel  m = new UserModel();
        m.setServerUrl("teset"+i);
        list.add(m);
    }
    baseMapper.insertBatchSomeColumn(list);
    System.out.println(JSON.toJSONString(list));
}

结果

bash 复制代码
  INSERT INTO t_reservation_device_config (server_url,create_time,update_time) VALUES   
('teset0',null,null)
 , 
('teset1',null,null)

[{"id":2,"serverUrl":"teset0"},{"id":3,"serverUrl":"teset1"}]

可以发现 批量插入成功,并返回了自增 Id

相关推荐
Knight_AL2 小时前
Spring Boot 多模块项目中优雅实现自动配置(基于 AutoConfiguration.imports)
java·spring boot·mybatis
indexsunny2 小时前
互联网大厂Java面试实战:从Spring Boot到微服务架构的三轮提问
java·spring boot·微服务·eureka·kafka·mybatis·spring security
Dontla3 小时前
boilerplate Introduction样板代码介绍(raw JDBC,Mybatis,productivity killer)
mybatis
没有bug.的程序员4 小时前
Spring Boot 数据访问:JPA 与 MyBatis 集成对比与性能优化深度解密
java·spring boot·性能优化·mybatis·jpa·集成对比
派大鑫wink4 小时前
【Day47】MyBatis 进阶:动态 SQL、关联查询(一对一 / 一对多)
数据库·sql·mybatis
派大鑫wink5 小时前
【Day48】MyBatis 注解开发:替代 XML 映射文件
xml·java·mybatis
小北方城市网6 小时前
JVM 调优实战指南:从 GC 频繁到性能稳定
jvm·数据库·spring boot·后端·mysql·mybatis
sin220115 小时前
MyBatis的执行流程
java·开发语言·mybatis
高山上有一只小老虎18 小时前
mybatisplus实现分页查询
java·spring boot·mybatis
独自破碎E1 天前
MyBatis Flex和MyBatis Plus的区别
java·开发语言·mybatis