All Downloads are FREE. Search and download functionalities are using the official Maven repository.

cn.meteor.common.database.methods.BatchInsert Maven / Gradle / Ivy

There is a newer version: 1.0.16
Show newest version
package cn.meteor.common.database.methods;// Copyright (C), Created on 2021-04-02

import cn.meteor.common.core.util.StringUtil;
import com.baomidou.mybatisplus.core.injector.AbstractMethod;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import org.apache.ibatis.executor.keygen.NoKeyGenerator;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlSource;

/**
 * 批量插入,1次提交代替 mybatisPlus 循环提交
 *
 * @author ths
 * @since 1.0.0
 */
public class BatchInsert extends AbstractMethod {

	@Override
	public MappedStatement injectMappedStatement(Class mapperClass, Class modelClass, TableInfo tableInfo) {
		final String sql = "";
		final String fieldSql = prepareFieldSql(tableInfo);
		final String valueSql = prepareValuesSqlForMysqlBatch(tableInfo);
		final String sqlResult = String.format(sql, tableInfo.getTableName(), fieldSql, valueSql);
		SqlSource sqlSource = languageDriver.createSqlSource(configuration, sqlResult, modelClass);
		return this.addInsertMappedStatement(mapperClass, modelClass, "batchInsert", sqlSource, new NoKeyGenerator(), null, null);
	}

	private String prepareFieldSql(TableInfo tableInfo) {
		StringBuilder fieldSql = new StringBuilder();
		// 联合主键有问题
		if (StringUtil.isNoneBlank(tableInfo.getKeyColumn())) {
			fieldSql.append(tableInfo.getKeyColumn()).append(",");
		}
		tableInfo.getFieldList().forEach(x -> {
			fieldSql.append(x.getColumn()).append(",");
		});
		fieldSql.delete(fieldSql.length() - 1, fieldSql.length());
		fieldSql.insert(0, "(");
		fieldSql.append(")");
		return fieldSql.toString();
	}

	private String prepareValuesSqlForMysqlBatch(TableInfo tableInfo) {
		final StringBuilder valueSql = new StringBuilder();
		valueSql.append("");
		if (StringUtil.isNoneBlank(tableInfo.getKeyColumn())) {
			valueSql.append("#{item.").append(tableInfo.getKeyProperty()).append("},");
		}
		tableInfo.getFieldList().forEach(x -> valueSql.append("#{item.").append(x.getProperty()).append("},"));
		valueSql.delete(valueSql.length() - 1, valueSql.length());
		valueSql.append("");
		return valueSql.toString();
	}
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy