MyBatis-Plus批量保存


springboot + mybatisPlus + mysql环境,批量保存的几种方法:

1.使用MybatisPlus自带的Iservice接口

BaseMapper中为提供批量插入接口,但是在com.baomidou.mybatisplus.extension.service.IService接口中提供了saveBatch批量插入方法。

1.1入门使用

  1. 新建一个接口,继承Iservice接口,泛型为被操作的实体类
package com.wsh.service;

import com.baomidou.mybatisplus.extension.service.IService;
import com.wsh.entity.Order;

public interface BatchInsertService extends IService<Order> {
}

  1. 创建一个方法,继承ServiceImpl,并且实现上述接口BatchInsertService
package com.wsh.service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wsh.mapper.OrderMapper;
import com.wsh.entity.Order;
import org.springframework.stereotype.Service;

@Service
public class BatchInsertServiceImpl extends ServiceImpl<OrderMapper,Order> implements BatchInsertService{

}

其中,extends ServiceImpl<OrderMapper,Order>Order是被操作的实体类Ordermapper是继承BaseMapper的自定义接口,如下:

package com.wsh.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.wsh.entity.Order;

// 使用mybatis-plus增强接口
public interface OrderMapper extends BaseMapper<Order> {

}
  1. 批量保存测试
package com.wsh;

import com.wsh.service.BatchInsertService;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import com.wsh.entity.Order;
import javax.annotation.Resource;

import java.util.ArrayList;
import java.util.Date;

@SpringBootTest
public class TestBatchInsertService {

    @Resource
    private BatchInsertService batchInsertService;

    @Test
    public void testBatchSave(){

        long start = System.currentTimeMillis();

        ArrayList<Order> orders = new ArrayList<>();

        for (int i = 0; i < 100000; i++) { //十万条数据

            Order order = new Order();
            order.setName("wsh"+i);
            order.setOrderDate(new Date());
            orders.add(order);
        }

        boolean b = batchInsertService.saveBatch(orders, 50);
        long end = System.currentTimeMillis();
        System.out.println("保存时间为:" + (end - start)); //73474
        System.out.println(b);
    }
}

测试结果为(部分展示):

==>  Preparing: INSERT INTO orders ( order_id, order_date, order_name ) VALUES ( ?, ?, ? ) 
==> Parameters: 0(Integer), 2021-07-28 10:16:42.773(Timestamp), wsh99951(String)
==> Parameters: 0(Integer), 2021-07-28 10:16:42.773(Timestamp), wsh99952(String)
==> Parameters: 0(Integer), 2021-07-28 10:16:42.773(Timestamp), wsh99953(String)
==> Parameters: 0(Integer), 2021-07-28 10:16:42.773(Timestamp), wsh99954(String)
==> Parameters: 0(Integer), 2021-07-28 10:16:42.773(Timestamp), wsh99955(String)
==> Parameters: 0(Integer), 2021-07-28 10:16:42.773(Timestamp), wsh99956(String)
==> Parameters: 0(Integer), 2021-07-28 10:16:42.773(Timestamp), wsh99957(String)
==> Parameters: 0(Integer), 2021-07-28 10:16:42.773(Timestamp), wsh99958(String)
==> Parameters: 0(Integer), 2021-07-28 10:16:42.773(Timestamp), wsh99959(String)
==> Parameters: 0(Integer), 2021-07-28 10:16:42.773(Timestamp), wsh99960(String)
==> Parameters: 0(Integer), 2021-07-28 10:16:42.773(Timestamp), wsh99961(String)
==> Parameters: 0(Integer), 2021-07-28 10:16:42.773(Timestamp), wsh99962(String)
==> Parameters: 0(Integer), 2021-07-28 10:16:42.773(Timestamp), wsh99963(String)
==> Parameters: 0(Integer), 2021-07-28 10:16:42.773(Timestamp), wsh99964(String)
==> Parameters: 0(Integer), 2021-07-28 10:16:42.773(Timestamp), wsh99965(String)
==> Parameters: 0(Integer), 2021-07-28 10:16:42.773(Timestamp), wsh99966(String)
==> Parameters: 0(Integer), 2021-07-28 10:16:42.773(Timestamp), wsh99967(String)
==> Parameters: 0(Integer), 2021-07-28 10:16:42.773(Timestamp), wsh99968(String)
==> Parameters: 0(Integer), 2021-07-28 10:16:42.773(Timestamp), wsh99969(String)
==> Parameters: 0(Integer), 2021-07-28 10:16:42.773(Timestamp), wsh99970(String)
==> Parameters: 0(Integer), 2021-07-28 10:16:42.773(Timestamp), wsh99971(String)
==> Parameters: 0(Integer), 2021-07-28 10:16:42.773(Timestamp), wsh99972(String)
==> Parameters: 0(Integer), 2021-07-28 10:16:42.773(Timestamp), wsh99973(String)
==> Parameters: 0(Integer), 2021-07-28 10:16:42.773(Timestamp), wsh99974(String)
==> Parameters: 0(Integer), 2021-07-28 10:16:42.773(Timestamp), wsh99975(String)
==> Parameters: 0(Integer), 2021-07-28 10:16:42.773(Timestamp), wsh99976(String)
==> Parameters: 0(Integer), 2021-07-28 10:16:42.773(Timestamp), wsh99977(String)
==> Parameters: 0(Integer), 2021-07-28 10:16:42.773(Timestamp), wsh99978(String)
==> Parameters: 0(Integer), 2021-07-28 10:16:42.773(Timestamp), wsh99979(String)
==> Parameters: 0(Integer), 2021-07-28 10:16:42.773(Timestamp), wsh99980(String)
==> Parameters: 0(Integer), 2021-07-28 10:16:42.773(Timestamp), wsh99981(String)
==> Parameters: 0(Integer), 2021-07-28 10:16:42.773(Timestamp), wsh99982(String)
==> Parameters: 0(Integer), 2021-07-28 10:16:42.773(Timestamp), wsh99983(String)
==> Parameters: 0(Integer), 2021-07-28 10:16:42.773(Timestamp), wsh99984(String)
==> Parameters: 0(Integer), 2021-07-28 10:16:42.773(Timestamp), wsh99985(String)
==> Parameters: 0(Integer), 2021-07-28 10:16:42.773(Timestamp), wsh99986(String)
==> Parameters: 0(Integer), 2021-07-28 10:16:42.773(Timestamp), wsh99987(String)
==> Parameters: 0(Integer), 2021-07-28 10:16:42.773(Timestamp), wsh99988(String)
==> Parameters: 0(Integer), 2021-07-28 10:16:42.773(Timestamp), wsh99989(String)
==> Parameters: 0(Integer), 2021-07-28 10:16:42.773(Timestamp), wsh99990(String)
==> Parameters: 0(Integer), 2021-07-28 10:16:42.773(Timestamp), wsh99991(String)
==> Parameters: 0(Integer), 2021-07-28 10:16:42.773(Timestamp), wsh99992(String)
==> Parameters: 0(Integer), 2021-07-28 10:16:42.773(Timestamp), wsh99993(String)
==> Parameters: 0(Integer), 2021-07-28 10:16:42.773(Timestamp), wsh99994(String)
==> Parameters: 0(Integer), 2021-07-28 10:16:42.773(Timestamp), wsh99995(String)
==> Parameters: 0(Integer), 2021-07-28 10:16:42.773(Timestamp), wsh99996(String)
==> Parameters: 0(Integer), 2021-07-28 10:16:42.773(Timestamp), wsh99997(String)
==> Parameters: 0(Integer), 2021-07-28 10:16:42.773(Timestamp), wsh99998(String)
==> Parameters: 0(Integer), 2021-07-28 10:16:42.773(Timestamp), wsh99999(String)
保存时间为:73474
true

1.2 原理方法

Iservice接口中saveBatch方法:

  /**
     * 插入(批量)
     *
     * @param entityList 实体对象集合
     * @param batchSize  插入批次数量
     */
    boolean saveBatch(Collection<T> entityList, int batchSize);

ServiceImpl.java实现类中的saveBatch方法:

    /**
    * 批量插入
    *
    * @param entityList ignore
    * @param batchSize ignore
    * @return ignore
    */
   @Transactional(rollbackFor = Exception.class)
   @Override
   public boolean saveBatch(Collection<T> entityList, int batchSize) {
       String sqlStatement = sqlStatement(SqlMethod.INSERT_ONE);
       try (SqlSession batchSqlSession = sqlSessionBatch()) {
           int i = 0;
           for (T anEntityList : entityList) {
               batchSqlSession.insert(sqlStatement, anEntityList);
               if (i >= 1 && i % batchSize == 0) {
                   batchSqlSession.flushStatements();
               }
               i++;
           }
           batchSqlSession.flushStatements();
       }
       return true;
   }
 

sqlSessionBatch

    /**
     * 批量操作 SqlSession
     */
    protected SqlSession sqlSessionBatch() {
        return SqlHelper.sqlSessionBatch(currentModelClass());
    }



    /**
     * 批量操作 SqlSession
     *
     * @param clazz 实体类
     * @return SqlSession
     */
    public static SqlSession sqlSessionBatch(Class<?> clazz) {
        // TODO 暂时让能用先,但日志会显示Closing non transactional SqlSession,因为这个并没有绑定.
        return GlobalConfigUtils.currentSessionFactory(clazz).openSession(ExecutorType.BATCH);
    }

注意:openSession(ExecutorType.BATCH),到这里就熟悉了。
插入十万条数据,时间为:73474

2.使用MybatisPlus自定义新增

2.1配置工作

注: 仅适用于MySQL

  1. 创建自定义数据方法注入类
package com.wsh.util;

import com.baomidou.mybatisplus.core.injector.AbstractMethod;
import com.baomidou.mybatisplus.core.injector.DefaultSqlInjector;
import com.baomidou.mybatisplus.extension.injector.methods.additional.InsertBatchSomeColumn;

import java.util.List;


public class EasySqlInjector extends DefaultSqlInjector {

 @Override
 public List<AbstractMethod> getMethodList(Class<?> mapperClass) {
     // 防止父类方法不可用
     List<AbstractMethod> methodList = super.getMethodList(mapperClass);
     methodList.add(new InsertBatchSomeColumn());
     return methodList;
 }
}
  1. 在MybatisPlus配置文件MybatisPlusConfig加入自定义
package com.wsh.config;

import com.baomidou.mybatisplus.extension.plugins.pagination.optimize.JsqlParserCountOptimize;
import com.wsh.util.EasySqlInjector;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;


@EnableTransactionManagement
@Configuration
@MapperScan("com.wsh.mapper")
public class MybatisPlusConfig {

    @Bean
    public EasySqlInjector easySqlInjector(){
        return new EasySqlInjector();
    }
}
  1. 扩展通用Mapper,支持数据批量插入,即:创建EasyBaseMapper接口继承BaseMapper
package com.wsh.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;

import java.util.Collection;

/**
 * @author suahng
 * @date 2021-07-21 20:47
 * @dec
 */
public interface EasyBaseMapper<T> extends BaseMapper<T> {


    /**
     * 批量插入,仅使用批量插入
     * @param entityList 实体列表
     * @return 影响行数
     */
    Integer insertBatchSomeColumn(Collection<T> entityList);
}
  1. 定义业务mapper接口,继承刚刚扩展的EasyBaseMapper
package com.wsh.mapper;
import com.wsh.entity.Order;
import org.springframework.stereotype.Repository;

@Repository
public interface EasyMapper extends EasyBaseMapper<Order> {
}
  1. 定义Service接口
package com.wsh.service;

import com.baomidou.mybatisplus.extension.service.IService;
import com.wsh.entity.Order;

import java.util.Collection;


public interface EasyService extends IService<Order> {

    /**
     * 批量插入,仅适用于 mysql
     * @param orderList
     * @return
     */
    public Integer BatchSave(Collection<Order> orderList);
}
  1. 定义service接口的实现类
package com.wsh.service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wsh.mapper.EasyBaseMapper;
import com.wsh.mapper.EasyMapper;
import com.wsh.entity.Order;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collection;


@Service
public class EasyServiceImpl extends ServiceImpl<EasyMapper, Order> implements EasyService{



    @Override
    public Integer BatchSave(Collection<Order> orderList) {
        return baseMapper.insertBatchSomeColumn(orderList);
    }
}

2.2 批量插入测试

package com.wsh;

import com.wsh.entity.Order;
import com.wsh.service.EasyServiceImpl;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;

@SpringBootTest
public class TestEasyService {

    @Resource
    EasyServiceImpl easyService;

    @Test
    public void testBatchSave(){

        long start = System.currentTimeMillis();

        ArrayList<Order> orders = new ArrayList<>();

        for (int i = 0; i < 100000; i++) {

            Order order = new Order();
            order.setName("hcy"+i);
            order.setOrderDate(new Date());
            orders.add(order);
        }

        Integer b = easyService.BatchSave(orders);
        long end = System.currentTimeMillis();
        System.out.println("保存时间为:" + (end - start));//6348 6093 4320
        System.out.println(b);
    }
}

结果:
在这里插入图片描述

0(Integer), 2021-07-28 11:28:02.54(Timestamp), hcy16065(String), 0(Integer), 2021-07-28 11:28:02.54(Timestamp), hcy16066(String), 0(Integer), 2021-07-28 11:28:02.54(Timestamp), hcy16067(String), 0(Integer), 2021-07-28 11:28:02.54(Timestamp), hcy16068(String), 0(Integer), 2021-07-28 11:28:02.54(Timestamp), hcy16069(String), 0(Integer), 2021-07-28 11:28:02.54(Timestamp), hcy16070(String), 0(Inte<...>.556(Timestamp), hcy99998(String), 0(Integer), 2021-07-28 11:28:02.556(Timestamp), hcy99999(String)
<==    Updates: 100000
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@1d50a7ca]
保存时间为:4223
100000

插入十万条数据,时间为:4223,比上一个方法减少了大约一半的时间。

  • 9
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
### 回答1: 您好,关于SpringBoot和MyBatis-Plus批量删除前后端代码,我可以为您提供一些信息。 首先,您需要在后端编写一个接口来处理批量删除的请求。可以使用MyBatis-Plus提供的批量删除方法来实现这一点。例如: ```java List<Integer> idList = Arrays.asList(1, 2, 3); int deleteCount = myService.removeByIds(idList); ``` 在前端,您需要创建一个表格或列表来显示需要删除的数据,并提供一个按钮来触发批量删除请求。可以使用JavaScript框架(如jQuery)来捕获用户点击事件并向后端发送请求。例如: ```javascript $('#deleteButton').click(function() { var idList = []; $('input[name="id"]:checked').each(function() { idList.push($(this).val()); }); $.ajax({ url: '/my-api/batch-delete', method: 'POST', data: { idList: idList }, success: function(response) { alert(response.message); }, error: function(jqXHR, textStatus, errorThrown) { alert('Error: ' + textStatus + ' - ' + errorThrown); } }); }); ``` 这里假设您的后端接口是`/my-api/batch-delete`,并且需要从前端接收一个名为`idList`的数组参数。 希望这些信息能对您有所帮助。如果您需要更具体的代码示例或其他方面的帮助,请随时提出。 ### 回答2: Spring Boot是一种用于创建基于Java的独立的、生产级别的应用程序的框架。MyBatis-Plus是一个建立在MyBatis之上的增强工具,提供了更多的功能和便利性。要批量删除前后端代码,可以按照以下步骤进行操作。 首先,确保你已经配置好了Spring Boot和MyBatis-Plus的环境,并且已经建立了数据库表和实体类。 一、前端代码删除 1. 打开前端代码所在的项目,找到要删除的文件或文件夹。 2. 右键点击选择“删除”或使用命令行删除相应文件。 3. 如果需要,可以在版本控制系统中提交并推送这些删除的更改。 二、后端代码删除 1. 打开后端代码所在的项目,找到要删除的文件或文件夹。 2. 右键点击选择“删除”或使用命令行删除相应文件。 3. 如果需要,可以在版本控制系统中提交并推送这些删除的更改。 三、数据库删除 1. 打开数据库管理工具,连接到你的数据库。 2. 找到与要删除的文件或文件夹对应的数据库表。 3. 使用SQL语句执行批量删除操作,例如:DELETE FROM 表名 WHERE 条件。 4. 如果需要,可以在数据库管理工具中提交和保存这些更改。 以上就是使用Spring Boot和MyBatis-Plus批量删除前后端代码的步骤。确保在删除代码之前备份相关文件和数据库,以防止数据丢失或无法恢复。同时,要小心地进行删除操作,确保不会删除错误的文件或数据。 ### 回答3: 如果要在Spring Boot中使用MyBatis-Plus进行批量删除操作,你需要完成以下几个步骤: 1. 首先,确保已经引入了Spring Boot和MyBatis-Plus的依赖包。可以在pom.xml文件中添加以下依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>${mybatis-plus.version}</version> </dependency> ``` 2. 定义一个实体类,表示要进行删除操作的数据表。可以使用注解@Table和@Id来指定对应的表名和主键字段。例如: ```java @Table("user") public class User { @Id private Long id; private String name; private Integer age; // 省略getter和setter方法 } ``` 3. 创建一个Mapper接口,使用MyBatis-Plus的注解来定义要进行的删除操作。例如,可以使用@Delete注解和@Param注解来指定要删除的条件: ```java public interface UserMapper extends BaseMapper<User> { @Delete("delete from user where age > #{minAge} and age < #{maxAge}") int deleteByAgeRange(@Param("minAge") Integer minAge, @Param("maxAge") Integer maxAge); } ``` 4. 在服务层(Service)中调用Mapper接口的方法来进行删除操作。例如,可以直接调用deleteByAgeRange方法来删除满足条件的数据: ```java @Service public class UserService { @Autowired private UserMapper userMapper; public void deleteByAgeRange(Integer minAge, Integer maxAge) { int result = userMapper.deleteByAgeRange(minAge, maxAge); // 处理删除操作的结果 } } ``` 5. 最后,在控制器层(Controller)中处理请求,并调用相应的服务层方法来完成批量删除操作。例如,可以定义一个RESTful接口来接收前端发送的删除请求: ```java @RestController public class UserController { @Autowired private UserService userService; @DeleteMapping("/users") public void deleteUsers(@RequestParam("minAge") Integer minAge, @RequestParam("maxAge") Integer maxAge) { userService.deleteByAgeRange(minAge, maxAge); // 返回删除结果或其他响应 } } ``` 以上就是使用Spring Boot和MyBatis-Plus进行批量删除操作的基本步骤。通过定义实体类、Mapper接口和服务层方法,再结合控制器层对前端请求的处理,可以方便地实现批量删除功能。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值