mybatis-plus批量插入
1、说明
使用mybatis-plus做数据批量插入时候,发现通常我们自定义mapper
接口继承 BaseMapper
。
@Mapper
public interface TerminalShopCityMapper extends BaseMapper<TerminalShopCityInfo> {
}
然而 BaseMapper
中不提供批量插入方法,只有单条插入方式。那如何批量插入呢?
2、批量插入
mybatis-plus 中提供了BaseMapper的子类 ServiceImpl
里有实现批量插入方法
public class ServiceImpl<M extends BaseMapper<T>, T> implements IService<T>{
public boolean insertBatch(List<T> entityList) {
return insertBatch(entityList, 30);
}
/**
* 批量插入
*
* @param entityList
* @param batchSize
* @return
*/
(rollbackFor = Exception.class)
public boolean insertBatch(List<T> entityList, int batchSize) {
if (CollectionUtils.isEmpty(entityList)) {
throw new IllegalArgumentException("Error: entityList must not be empty");
}
try (SqlSession batchSqlSession = sqlSessionBatch()) {
int size = entityList.size();
String sqlStatement = sqlStatement(SqlMethod.INSERT_ONE);
for (int i = 0; i < size; i++) {
batchSqlSession.insert(sqlStatement, entityList.get(i));
if (i >= 1 && i % batchSize == 0) {
batchSqlSession.flushStatements();
}
}
batchSqlSession.flushStatements();
} catch (Throwable e) {
throw new MybatisPlusException("Error: Cannot execute insertBatch Method. Cause", e);
}
return true;
}
}
① 增加实现类
class ShopCityWapperImpl extends ServiceImpl<TerminalShopCityMapper, TerminalShopCityInfo> {
}
public
② 引用实现类
@Service
@Slf4j
public class ShopServiceImpl implements ShopService {
@Autowired
private ShopCityWapperImpl wapperImpl;
}
然后调用insertBatch方法即可。
wapperImpl.insertBatch(doList);
执行完成,查看数据库如下图