|
@@ -0,0 +1,58 @@
|
|
|
+package com.chelvc.framework.database.mapper;
|
|
|
+
|
|
|
+import java.util.List;
|
|
|
+
|
|
|
+import com.baomidou.mybatisplus.annotation.IdType;
|
|
|
+import com.baomidou.mybatisplus.core.enums.SqlMethod;
|
|
|
+import com.baomidou.mybatisplus.core.injector.AbstractMethod;
|
|
|
+import com.baomidou.mybatisplus.core.metadata.TableFieldInfo;
|
|
|
+import com.baomidou.mybatisplus.core.metadata.TableInfo;
|
|
|
+import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
|
|
|
+import com.chelvc.framework.common.util.StringUtils;
|
|
|
+import org.apache.ibatis.executor.keygen.Jdbc3KeyGenerator;
|
|
|
+import org.apache.ibatis.executor.keygen.KeyGenerator;
|
|
|
+import org.apache.ibatis.executor.keygen.NoKeyGenerator;
|
|
|
+import org.apache.ibatis.mapping.MappedStatement;
|
|
|
+import org.apache.ibatis.mapping.SqlSource;
|
|
|
+
|
|
|
+/**
|
|
|
+ * 插入或忽略方法实现
|
|
|
+ *
|
|
|
+ * @author Woody
|
|
|
+ * @date 2024/2/27
|
|
|
+ */
|
|
|
+public class InsertIgnoreMethod extends AbstractMethod {
|
|
|
+ @Override
|
|
|
+ public MappedStatement injectMappedStatement(Class<?> mapperClass, Class<?> modelClass, TableInfo tableInfo) {
|
|
|
+ String keyColumn = null;
|
|
|
+ String keyProperty = null;
|
|
|
+ KeyGenerator keyGenerator;
|
|
|
+ if (StringUtils.isEmpty(tableInfo.getKeyProperty())) {
|
|
|
+ keyGenerator = new NoKeyGenerator();
|
|
|
+ } else if (tableInfo.getIdType() == IdType.AUTO) {
|
|
|
+ keyColumn = tableInfo.getKeyColumn();
|
|
|
+ keyProperty = tableInfo.getKeyProperty();
|
|
|
+ keyGenerator = new Jdbc3KeyGenerator();
|
|
|
+ } else if (tableInfo.getKeySequence() != null) {
|
|
|
+ keyColumn = tableInfo.getKeyColumn();
|
|
|
+ keyProperty = tableInfo.getKeyProperty();
|
|
|
+ String method = this.getMethod(SqlMethod.INSERT_ONE);
|
|
|
+ keyGenerator = TableInfoHelper.genKeyGenerator(method, tableInfo, this.builderAssistant);
|
|
|
+ } else {
|
|
|
+ keyGenerator = new NoKeyGenerator();
|
|
|
+ }
|
|
|
+ List<TableFieldInfo> fields = tableInfo.getFieldList();
|
|
|
+ String columns = tableInfo.getKeyInsertSqlColumn(false) +
|
|
|
+ this.filterTableFieldInfo(fields, null, TableFieldInfo::getInsertSqlColumn, EMPTY);
|
|
|
+ columns = columns.substring(0, columns.length() - 1);
|
|
|
+ String properties = tableInfo.getKeyInsertSqlProperty(null, false) +
|
|
|
+ this.filterTableFieldInfo(fields, null, i -> i.getInsertSqlProperty(null), EMPTY);
|
|
|
+ properties = properties.substring(0, properties.length() - 1);
|
|
|
+ String script = String.format("<script>\nINSERT IGNORE INTO %s (%s) VALUES (%s)\n</script>",
|
|
|
+ tableInfo.getTableName(), columns, properties);
|
|
|
+ SqlSource source = this.languageDriver.createSqlSource(this.configuration, script, modelClass);
|
|
|
+ return this.addInsertMappedStatement(
|
|
|
+ mapperClass, modelClass, "insertIgnore", source, keyGenerator, keyProperty, keyColumn
|
|
|
+ );
|
|
|
+ }
|
|
|
+}
|