1、编写SQL注入器
java
复制代码
@Component("batchInsertInjector")
public class BatchInsertInjector extends DefaultSqlInjector {
@Override
public List<AbstractMethod> getMethodList(Class<?> mapperClass) {
List<AbstractMethod> methodList = super.getMethodList(mapperClass);
methodList.add(new InsertBatchSomeColumn());
return methodList;
}
}
2、自定义Mapper继承BaseMapper
java
复制代码
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
java
复制代码
@Mapper
public interface LibraryBusinessInfoMapper extends AbstractMapper<LibraryBusinessInfo> {
}
4、使用批量插入方法
java
复制代码
@Autowired
private LibraryBusinessInfoMapper libraryBusinessInfoMapper;
@Override
@Transactional
public int batchAdd(List<AddLibraryInfoReqVo> addLibraryInfoReqVos) {
List<LibraryInfo> libraryInfos = ReqVo2Entity.INSTANCE.addLibraryInfos2LibraryInfos(addLibraryInfoReqVos);
libraryInfoMapper.segmentBatchInsert(libraryInfos);
return libraryInfos.size();
}