MybatisPlus默认提供的批量插入方法实际上是单条插入的,跟我们预期的不一样。其实MybatisPlus提供了真正的批量插入方法,但是只适用于MYSQL,所以并没有放出来,需要自己去拓展一下。
依赖版本:
<dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.4.0</version> </dependency>
新建拓展类:
import com.baomidou.mybatisplus.core.injector.AbstractMethod; import com.baomidou.mybatisplus.core.injector.DefaultSqlInjector; import com.baomidou.mybatisplus.extension.injector.methods.InsertBatchSomeColumn; import org.springframework.stereotype.Component; import java.util.List; /** * 211013 * 拓展mybatisPlus 支持批量插入 */ @Component public class ExpandSqlInjector extends DefaultSqlInjector { @Override public List<AbstractMethod> getMethodList(Class<?> mapperClass) { List<AbstractMethod> methodList = super.getMethodList(mapperClass); methodList.add(new InsertBatchSomeColumn()); return methodList; } }
创建新的ExpandBaseMapper:
import com.baomidou.mybatisplus.core.mapper.BaseMapper; import java.util.Collection; /** * 211013 * 真正实现批量插入的拓展接口 * * @param <T> */ public interface ExpandBaseMapper<T> extends BaseMapper<T> { /** * 批量插入 仅适用于mysql * * @param entityList 实体列表 * @return 影响行数 */ Integer insertBatchSomeColumn(Collection<T> entityList); }
注入bean:
import com.baomidou.mybatisplus.annotation.DbType; import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor; import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor; import org.mybatis.spring.annotation.MapperScan; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.transaction.annotation.EnableTransactionManagement; /** * MyBatis配置类 * Created by xc on 2020/9/4. */ @Configuration @EnableTransactionManagement @MapperScan({"com.xc.xcspringboot.mapper,com.xc.xcspringboot.*.mapper"}) public class MyBatisConfig { /** * 分页插件: PaginationInnerInterceptor */ @Bean public MybatisPlusInterceptor mybatisPlusInterceptor() { MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor(); interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL)); return interceptor; } @Bean public ExpandSqlInjector expandSqlInjector() { return new ExpandSqlInjector(); } }
在自己的mapper中继承ExpandBaseMapper,调用insertBatchSomeColumn即可实现真正的批量插入。
public interface TbUserMapper extends ExpandBaseMapper<TbUser> { }
文章来源:https://blog.csdn.net/qq_18630487/article/details/111153883