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

相关推荐
qq_2142258719 小时前
学生成绩管理系统Java实战(Spring Boot+MyBatis Plus)
java·spring boot·其他·mybatis
珹洺20 小时前
MyBatis实战指南(一)MyBatis入门基础与利用IDEA从零开始搭建你的第一个MyBatis系统
java·数据库·ide·intellij-idea·mybatis
我爱Jack2 天前
Mybatis操作数据库(2)
java·数据库·mybatis
prinrf('千寻)2 天前
MyBatis-Plus 的 updateById 方法不更新 null 值属性的问题
java·开发语言·mybatis
linab1123 天前
mybatis中的resultMap的association及collectio的使用
java·开发语言·mybatis
Code哈哈笑3 天前
【图书管理系统】用户注册系统实现详解
数据库·spring boot·后端·mybatis
Code哈哈笑3 天前
【基于Spring Boot 的图书购买系统】深度讲解 用户注册的前后端交互,Mapper操作MySQL数据库进行用户持久化
数据库·spring boot·后端·mysql·mybatis·交互
lyrhhhhhhhh3 天前
MyBatis 延迟加载与缓存
sql·缓存·mybatis
菜鸟蹦迪3 天前
学习记录:mybatis和jdbc实现数据表作为参数的相关的sql操作
sql·学习·mybatis