1、编写SQL注入器
@Component("batchInsertInjector")
public class BatchInsertInjector extends DefaultSqlInjector {@Overridepublic List<AbstractMethod> getMethodList(Class<?> mapperClass) {List<AbstractMethod> methodList = super.getMethodList(mapperClass);methodList.add(new InsertBatchSomeColumn());return methodList;}
}
2、自定义Mapper继承BaseMapper
public interface AbstractMapper<T> extends BaseMapper<T> {Integer SIZE_LIMIT = 3000;/*** 批量插入,借助mybatis-plush的injector实现* @param entities*/void insertBatchSomeColumn(@Param("list") List<T> entities);/*** 分段批量插入* @param entities*/default void segmentBatchInsert(List<T> entities){if (CollectionUtils.isEmpty(entities)) {return;}List<List<T>> partition = Lists.partition(entities, SIZE_LIMIT);for (List<T> part : partition) {insertBatchSomeColumn(part);}}
}
3、实体类的mapper继承自定义mapper
@Mapper
public interface LibraryBusinessInfoMapper extends AbstractMapper<LibraryBusinessInfo> {
}
4、使用批量插入方法
@Autowiredprivate LibraryBusinessInfoMapper libraryBusinessInfoMapper;@Override@Transactionalpublic int batchAdd(List<AddLibraryInfoReqVo> addLibraryInfoReqVos) {List<LibraryInfo> libraryInfos = ReqVo2Entity.INSTANCE.addLibraryInfos2LibraryInfos(addLibraryInfoReqVos);libraryInfoMapper.segmentBatchInsert(libraryInfos);return libraryInfos.size();}