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

相关推荐
面向星辰4 小时前
sql基本增删改查语句汇总
数据库·sql·mybatis
凌波粒10 小时前
SpringMVC基础教程(3)--SSM框架整合
java·sql·spring·intellij-idea·mybatis
humors2211 天前
服务端开发案例(不定期更新)
java·数据库·后端·mysql·mybatis·excel
朝新_1 天前
【实战】动态 SQL + 统一 Result + 登录校验:图书管理系统(下)
xml·java·数据库·sql·mybatis
百***84451 天前
SpringBoot(整合MyBatis + MyBatis-Plus + MyBatisX插件使用)
spring boot·tomcat·mybatis
q***71851 天前
Spring Boot 集成 MyBatis 全面讲解
spring boot·后端·mybatis
原来是好奇心1 天前
Spring Boot缓存实战:@Cacheable注解详解与性能优化
java·spring·mybatis·springboot
战血石LoveYY1 天前
mybatis踩坑值 <if test=> 不能用大写AND
mybatis
C++chaofan1 天前
基于session实现短信登录
java·spring boot·redis·mybatis·拦截器·session
神仙别闹1 天前
基于SpringMVC+Spring+MyBatis开发的个人博客网站
java·spring·mybatis