这篇文章将为大家详细讲解有关MybatisPlus如何实现批量插入,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。
再数据同步或者幂等场景下,常常需要设置唯一索引来避免重复请求,select and update
效率低,且并发时还是会报错,并不友好,那么可以用Mysql的Insert ignore语法来优化。
MybatisPlus官方并没有针此处场景进行支持
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.2.0</version>
<exclusions>
<exclusion>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
</exclusion>
</exclusions>
</dependency>
因为只需要改造insertBatchSomeColumn
方法,那直接CV就好
insertBatchSomeColumn
方法属于mybatis plus
官方扩展包中
sql模板
public class InsertIgnoreBatchAllColumn extends AbstractMethod {
/**
* mapper 对应的方法名
*/
private static final String MAPPER_METHOD = "insertIgnoreBatchAllColumn";
/**
* 字段筛选条件
*/
@Setter
@Accessors(chain = true)
private Predicate<TableFieldInfo> predicate;
@SuppressWarnings("Duplicates")
@Override
public MappedStatement injectMappedStatement(Class<?> mapperClass, Class<?> modelClass, TableInfo tableInfo) {
KeyGenerator keyGenerator = new NoKeyGenerator();
SqlMethod sqlMethod = SqlMethod.INSERT_ONE;
String sqlTemplate = "<script>\nINSERT IGNORE INTO %s %s VALUES %s\n</script>";
List<TableFieldInfo> fieldList = tableInfo.getFieldList();
String insertSqlColumn = tableInfo.getKeyInsertSqlColumn(false) +
this.filterTableFieldInfo(fieldList, predicate, TableFieldInfo::getInsertSqlColumn, EMPTY);
String columnScript = LEFT_BRACKET + insertSqlColumn.substring(0, insertSqlColumn.length() - 1) + RIGHT_BRACKET;
String insertSqlProperty = tableInfo.getKeyInsertSqlProperty(ENTITY_DOT, false) +
this.filterTableFieldInfo(fieldList, predicate, i -> i.getInsertSqlProperty(ENTITY_DOT), EMPTY);
insertSqlProperty = LEFT_BRACKET + insertSqlProperty.substring(0, insertSqlProperty.length() - 1) + RIGHT_BRACKET;
String valuesScript = SqlScriptUtils.convertForeach(insertSqlProperty, "list", null, ENTITY, COMMA);
String keyProperty = null;
String keyColumn = null;
// 表包含主键处理逻辑,如果不包含主键当普通字段处理
if (StringUtils.isNotEmpty(tableInfo.getKeyProperty())) {
if (tableInfo.getIdType() == IdType.AUTO) {
/* 自增主键 */
keyGenerator = new Jdbc3KeyGenerator();
keyProperty = tableInfo.getKeyProperty();
keyColumn = tableInfo.getKeyColumn();
} else {
if (null != tableInfo.getKeySequence()) {
keyGenerator = TableInfoHelper.genKeyGenerator(tableInfo, builderAssistant, sqlMethod.getMethod(), languageDriver);
keyProperty = tableInfo.getKeyProperty();
keyColumn = tableInfo.getKeyColumn();
}
}
}
String sql = String.format(sqlTemplate, tableInfo.getTableName(), columnScript, valuesScript);
SqlSource sqlSource = languageDriver.createSqlSource(configuration, sql, modelClass);
return this.addInsertMappedStatement(mapperClass, modelClass, MAPPER_METHOD, sqlSource, keyGenerator, keyProperty, keyColumn);
}
}
注入sql
public class CustomerSqlInjector extends DefaultSqlInjector {
@Override
public List<AbstractMethod> getMethodList(Class<?> mapperClass) {
List<AbstractMethod> methodList = super.getMethodList(mapperClass);
methodList.add(new InsertIgnoreBatchAllColumn());
return methodList;
}
}
通用mapper
public interface CommonMapper<T> extends BaseMapper<T> {
/**
* 全量插入,等价于insert,忽略唯一索引冲突的行
* {@link InsertIgnoreBatchAllColumn}
*
* @param entityList
* @return
*/
int insertIgnoreBatchAllColumn(List<T> entityList);
}
通用Service
public class CommonServiceImpl<M extends CommonMapper<T>, T> extends ServiceImpl<M, T> {
@Transactional(rollbackFor = Exception.class)
public boolean fastSaveIgnoreBatch(List<T> list, int batchSize) {
if(CollectionUtils.isEmpty(list)) {
return true;
}
batchSize = batchSize < 1 ? BATCH_SIZE : batchSize;
if(list.size() <= batchSize) {
return retBool(baseMapper.insertIgnoreBatchAllColumn(list));
}
for (int fromIdx = 0 , endIdx = batchSize ; ; fromIdx += batchSize, endIdx += batchSize) {
if(endIdx > list.size()) {
endIdx = list.size();
}
baseMapper.insertIgnoreBatchAllColumn(list.subList(fromIdx, endIdx));
if(endIdx == list.size()) {
return true;
}
}
}
@Transactional(rollbackFor = Exception.class)
public boolean fastSaveIgnoreBatch(List<T> list) {
return fastSaveIgnoreBatch(list, BATCH_SIZE);
}
}
关于“MybatisPlus如何实现批量插入”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,使各位可以学到更多知识,如果觉得文章不错,请把它分享出去让更多的人看到。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。
原文链接:https://my.oschina.net/teddyIH/blog/4548046