mybatis-generator

InsertIgnorePlugin

package com.itfsw.mybatis.generator.plugins;

import com.itfsw.mybatis.generator.plugins.utils.*;
import org.mybatis.generator.api.IntrospectedColumn;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.dom.OutputUtilities;
import org.mybatis.generator.api.dom.java.*;
import org.mybatis.generator.api.dom.xml.Attribute;
import org.mybatis.generator.api.dom.xml.Document;
import org.mybatis.generator.api.dom.xml.TextElement;
import org.mybatis.generator.api.dom.xml.XmlElement;
import org.mybatis.generator.codegen.mybatis3.ListUtilities;
import org.mybatis.generator.codegen.mybatis3.MyBatis3FormattingUtilities;
import org.mybatis.generator.config.GeneratedKey;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;

public class InsertIgnorePlugin extends BasePlugin {
    public static final String METHOD_INSERT_IGNORE = "insertIgnore";  // 方法名
    public static final String METHOD_INSERT_SELECTIVE_IGNORE = "insertSelectiveIgnore";  // 方法名
    /**
     * {@inheritDoc}
     */
    @Override
    public boolean validate(List<String> warnings) {
        // 插件使用前提是数据库为MySQL或者SQLserver,因为返回主键使用了JDBC的getGenereatedKeys方法获取主键
        if ("com.mysql.jdbc.Driver".equalsIgnoreCase(this.getContext().getJdbcConnectionConfiguration().getDriverClass()) == false
            && "com.microsoft.jdbc.sqlserver.SQLServer".equalsIgnoreCase(this.getContext().getJdbcConnectionConfiguration().getDriverClass()) == false
            && "com.microsoft.sqlserver.jdbc.SQLServerDriver".equalsIgnoreCase(this.getContext().getJdbcConnectionConfiguration().getDriverClass()) == false
            && "com.mysql.cj.jdbc.Driver".equalsIgnoreCase(this.getContext().getJdbcConnectionConfiguration().getDriverClass()) == false) {
            warnings.add("itfsw:插件" + this.getClass().getTypeName() + "插件使用前提是数据库为MySQL或者SQLserver,因为返回主键使用了JDBC的getGenereatedKeys方法获取主键!");
            return false;
        }

        // 插件使用前提是使用了ModelColumnPlugin插件
        if (!PluginTools.checkDependencyPlugin(getContext(), ModelColumnPlugin.class)) {
            warnings.add("itfsw:插件" + this.getClass().getTypeName() + "插件需配合com.itfsw.mybatis.generator.plugins.ModelColumnPlugin插件使用!");
            return false;
        }

        return super.validate(warnings);
    }

    @Override
    public boolean clientGenerated(Interface interfaze, TopLevelClass topLevelClass,
                                   IntrospectedTable introspectedTable) {
        addMethodInsertIgnore(interfaze, introspectedTable);
        logger.debug("itfsw(InsertIgnorePlugin):" + interfaze.getType().getShortName() + "增加insertIgnore方法。");
        addMethodSelectiveInsertIgnore(interfaze, introspectedTable);
        logger.debug("itfsw(InsertIgnorePlugin):" + interfaze.getType().getShortName() + "增加insertSelectiveIgnore方法。");
        return super.clientGenerated(interfaze, topLevelClass, introspectedTable);
    }


    private void addMethodInsertIgnore(Interface interfaze, IntrospectedTable introspectedTable) {
        Method method = new Method();

        method.setReturnType(FullyQualifiedJavaType.getIntInstance());
        method.setVisibility(JavaVisibility.PUBLIC);
        method.setName(METHOD_INSERT_IGNORE);

        FullyQualifiedJavaType parameterType = introspectedTable.getRules()
            .calculateAllFieldsClass();

        Set<FullyQualifiedJavaType> importedTypes = new TreeSet<FullyQualifiedJavaType>();
        importedTypes.add(parameterType);
        method.addParameter(new Parameter(parameterType, "record")); //$NON-NLS-1$

        commentGenerator.addGeneralMethodComment(method, introspectedTable);
        // interface 增加方法
        FormatTools.addMethodWithBestPosition(interfaze, method);
    }

    private void addMethodSelectiveInsertIgnore(Interface interfaze, IntrospectedTable introspectedTable) {
        Method method = new Method();

        method.setReturnType(FullyQualifiedJavaType.getIntInstance());
        method.setVisibility(JavaVisibility.PUBLIC);
        method.setName(METHOD_INSERT_SELECTIVE_IGNORE);

        FullyQualifiedJavaType parameterType = introspectedTable.getRules()
            .calculateAllFieldsClass();

        Set<FullyQualifiedJavaType> importedTypes = new TreeSet<FullyQualifiedJavaType>();
        importedTypes.add(parameterType);
        method.addParameter(new Parameter(parameterType, "record")); //$NON-NLS-1$

        commentGenerator.addGeneralMethodComment(method, introspectedTable);
        // interface 增加方法
        FormatTools.addMethodWithBestPosition(interfaze, method);
    }

    @Override
    public boolean sqlMapDocumentGenerated(Document document, IntrospectedTable introspectedTable) {
        XmlElement parentElement = document.getRootElement();
        // 1. insertIgnore
        XmlElement insertIgnore = new XmlElement(METHOD_INSERT_IGNORE);
        commentGenerator.addComment(insertIgnore);
        parentElement.addElement(insertIgnore);
        sqlMapInsertIgnoreElementGenerated(insertIgnore, introspectedTable);
        logger.debug("itfsw(InsertIgnorePlugin):" + introspectedTable.getMyBatis3XmlMapperFileName() + "增加insertIgnore实现方法。");

        // 2. insertSelectiveIgnore
        XmlElement insertSelectiveIgnore  = new XmlElement(METHOD_INSERT_SELECTIVE_IGNORE);
        commentGenerator.addComment(insertSelectiveIgnore);
        parentElement.addElement(insertSelectiveIgnore);
        sqlMapInsertSelectiveIgnoreElementGenerated(insertSelectiveIgnore, introspectedTable);
        logger.debug("itfsw(InsertIgnorePlugin):" + introspectedTable.getMyBatis3XmlMapperFileName() + "增加insertSelectiveIgnore实现方法。");
        return true;
    }

    private boolean sqlMapInsertIgnoreElementGenerated(XmlElement element, IntrospectedTable introspectedTable) {
        // 清空
        XmlElement answer = new XmlElement("insert");
        answer.addAttribute(new Attribute("id", METHOD_INSERT_IGNORE));
        FullyQualifiedJavaType parameterType = introspectedTable.getRules().calculateAllFieldsClass();
        answer.addAttribute(new Attribute("parameterType", //$NON-NLS-1$
            parameterType.getFullyQualifiedName()));
        commentGenerator.addComment(answer);


        GeneratedKey gk = introspectedTable.getGeneratedKey();
        if (gk != null) {
            IntrospectedColumn introspectedColumn = introspectedTable
                .getColumn(gk.getColumn());
            // if the column is null, then it's a configuration error. The
            // warning has already been reported
            if (introspectedColumn != null) {
                if (gk.isJdbcStandard()) {
                    answer.addAttribute(new Attribute(
                        "useGeneratedKeys", "true")); //$NON-NLS-1$ //$NON-NLS-2$
                    answer.addAttribute(new Attribute(
                        "keyProperty", introspectedColumn.getJavaProperty())); //$NON-NLS-1$
                    answer.addAttribute(new Attribute(
                        "keyColumn", introspectedColumn.getActualColumnName())); //$NON-NLS-1$
                } else {
                    answer.addElement(getSelectKey(introspectedColumn, gk));
                }
            }
        }

        StringBuilder insertClause = new StringBuilder();

        insertClause.append("insert ignore into "); //$NON-NLS-1$
        insertClause.append(introspectedTable
            .getFullyQualifiedTableNameAtRuntime());
        insertClause.append(" ("); //$NON-NLS-1$

        StringBuilder valuesClause = new StringBuilder();
        valuesClause.append("values ("); //$NON-NLS-1$

        List<String> valuesClauses = new ArrayList<String>();
        List<IntrospectedColumn> columns = ListUtilities.removeIdentityAndGeneratedAlwaysColumns(introspectedTable.getAllColumns());
        for (int i = 0; i < columns.size(); i++) {
            IntrospectedColumn introspectedColumn = columns.get(i);

            insertClause.append(MyBatis3FormattingUtilities
                .getEscapedColumnName(introspectedColumn));
            valuesClause.append(MyBatis3FormattingUtilities
                .getParameterClause(introspectedColumn));
            if (i + 1 < columns.size()) {
                insertClause.append(", "); //$NON-NLS-1$
                valuesClause.append(", "); //$NON-NLS-1$
            }

            if (valuesClause.length() > 80) {
                answer.addElement(new TextElement(insertClause.toString()));
                insertClause.setLength(0);
                OutputUtilities.xmlIndent(insertClause, 1);

                valuesClauses.add(valuesClause.toString());
                valuesClause.setLength(0);
                OutputUtilities.xmlIndent(valuesClause, 1);
            }
        }

        insertClause.append(')');
        answer.addElement(new TextElement(insertClause.toString()));

        valuesClause.append(')');
        valuesClauses.add(valuesClause.toString());

        for (String clause : valuesClauses) {
            answer.addElement(new TextElement(clause));
        }

        XmlElementTools.replaceXmlElement(element, answer);
        return super.sqlMapInsertSelectiveElementGenerated(element, introspectedTable);
    }

    private boolean sqlMapInsertSelectiveIgnoreElementGenerated(XmlElement element, IntrospectedTable introspectedTable) {
        // 清空
        XmlElement answer = new XmlElement("insert");
        answer.addAttribute(new Attribute("id", METHOD_INSERT_SELECTIVE_IGNORE));
        FullyQualifiedJavaType parameterType = introspectedTable.getRules().calculateAllFieldsClass();
        answer.addAttribute(new Attribute("parameterType", //$NON-NLS-1$
            parameterType.getFullyQualifiedName()));
        commentGenerator.addComment(answer);


        GeneratedKey gk = introspectedTable.getGeneratedKey();
        if (gk != null) {
            IntrospectedColumn introspectedColumn = introspectedTable
                .getColumn(gk.getColumn());
            // if the column is null, then it's a configuration error. The
            // warning has already been reported
            if (introspectedColumn != null) {
                if (gk.isJdbcStandard()) {
                    answer.addAttribute(new Attribute(
                        "useGeneratedKeys", "true")); //$NON-NLS-1$ //$NON-NLS-2$
                    answer.addAttribute(new Attribute(
                        "keyProperty", introspectedColumn.getJavaProperty())); //$NON-NLS-1$
                    answer.addAttribute(new Attribute(
                        "keyColumn", introspectedColumn.getActualColumnName())); //$NON-NLS-1$
                } else {
                    answer.addElement(getSelectKey(introspectedColumn, gk));
                }
            }
        }
        StringBuilder sb = new StringBuilder();

        sb.append("insert ignore into "); //$NON-NLS-1$
        sb.append(introspectedTable.getFullyQualifiedTableNameAtRuntime());
        answer.addElement(new TextElement(sb.toString()));

        XmlElement insertTrimElement = new XmlElement("trim"); //$NON-NLS-1$
        insertTrimElement.addAttribute(new Attribute("prefix", "(")); //$NON-NLS-1$ //$NON-NLS-2$
        insertTrimElement.addAttribute(new Attribute("suffix", ")")); //$NON-NLS-1$ //$NON-NLS-2$
        insertTrimElement.addAttribute(new Attribute("suffixOverrides", ",")); //$NON-NLS-1$ //$NON-NLS-2$
        answer.addElement(insertTrimElement);

        XmlElement valuesTrimElement = new XmlElement("trim"); //$NON-NLS-1$
        valuesTrimElement.addAttribute(new Attribute("prefix", "values (")); //$NON-NLS-1$ //$NON-NLS-2$
        valuesTrimElement.addAttribute(new Attribute("suffix", ")")); //$NON-NLS-1$ //$NON-NLS-2$
        valuesTrimElement.addAttribute(new Attribute("suffixOverrides", ",")); //$NON-NLS-1$ //$NON-NLS-2$
        answer.addElement(valuesTrimElement);

        for (IntrospectedColumn introspectedColumn : ListUtilities.removeIdentityAndGeneratedAlwaysColumns(introspectedTable
            .getAllColumns())) {

            if (introspectedColumn.isSequenceColumn()
                || introspectedColumn.getFullyQualifiedJavaType().isPrimitive()) {
                // if it is a sequence column, it is not optional
                // This is required for MyBatis3 because MyBatis3 parses
                // and calculates the SQL before executing the selectKey

                // if it is primitive, we cannot do a null check
                sb.setLength(0);
                sb.append(MyBatis3FormattingUtilities
                    .getEscapedColumnName(introspectedColumn));
                sb.append(',');
                insertTrimElement.addElement(new TextElement(sb.toString()));

                sb.setLength(0);
                sb.append(MyBatis3FormattingUtilities
                    .getParameterClause(introspectedColumn));
                sb.append(',');
                valuesTrimElement.addElement(new TextElement(sb.toString()));

                continue;
            }

            sb.setLength(0);
            sb.append(introspectedColumn.getJavaProperty());
            sb.append(" != null"); //$NON-NLS-1$
            XmlElement insertNotNullElement = new XmlElement("if"); //$NON-NLS-1$
            insertNotNullElement.addAttribute(new Attribute(
                "test", sb.toString())); //$NON-NLS-1$

            sb.setLength(0);
            sb.append(MyBatis3FormattingUtilities
                .getEscapedColumnName(introspectedColumn));
            sb.append(',');
            insertNotNullElement.addElement(new TextElement(sb.toString()));
            insertTrimElement.addElement(insertNotNullElement);

            sb.setLength(0);
            sb.append(introspectedColumn.getJavaProperty());
            sb.append(" != null"); //$NON-NLS-1$
            XmlElement valuesNotNullElement = new XmlElement("if"); //$NON-NLS-1$
            valuesNotNullElement.addAttribute(new Attribute(
                "test", sb.toString())); //$NON-NLS-1$

            sb.setLength(0);
            sb.append(MyBatis3FormattingUtilities
                .getParameterClause(introspectedColumn));
            sb.append(',');
            valuesNotNullElement.addElement(new TextElement(sb.toString()));
            valuesTrimElement.addElement(valuesNotNullElement);
        }

        XmlElementTools.replaceXmlElement(element, answer);
        return super.sqlMapInsertSelectiveElementGenerated(element, introspectedTable);
    }

}

SelectiveExtensionMethodPlugin

/*
 * Copyright (c) 2018.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.itfsw.mybatis.generator.plugins;

import com.itfsw.mybatis.generator.plugins.utils.*;
import com.itfsw.mybatis.generator.plugins.utils.hook.IIncrementsPluginHook;
import com.itfsw.mybatis.generator.plugins.utils.hook.IOptimisticLockerPluginHook;
import com.itfsw.mybatis.generator.plugins.utils.hook.IUpsertPluginHook;
import org.mybatis.generator.api.IntrospectedColumn;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.dom.java.*;
import org.mybatis.generator.api.dom.xml.*;
import org.mybatis.generator.codegen.mybatis3.ListUtilities;
import org.mybatis.generator.config.GeneratedKey;

import java.util.List;
import java.util.Set;
import java.util.TreeSet;

/**
 * ---------------------------------------------------------------------------
 * Selective 增强插件
 * 解决老版本兼容采用新增方法而不是直接修改,不能重写主要是mybatis不支持重写
 * ---------------------------------------------------------------------------
 * @time:2018/9/04 15:39
 * ---------------------------------------------------------------------------
 */
public class SelectiveExtensionMethodPlugin extends BasePlugin implements IUpsertPluginHook, IOptimisticLockerPluginHook {
    public static final String METHOD_INSERT_SELECTIVE_EXT= "insertSelectiveExt";  // 方法名
    public static final String METHOD_UPDATE_BY_EXAMPLE_SELECTIVE_EXT = "updateByExampleSelectiveExt";  // 方法名
    public static final String METHOD_UPDATE_BY_PRIMARY_KEY_SELECTIVE_EXT = "updateByPrimaryKeySelectiveExt";  // 方法名


    /**
     * {@inheritDoc}
     */
    @Override
    public boolean validate(List<String> warnings) {

        // 插件使用前提是使用了ModelColumnPlugin插件
        if (!PluginTools.checkDependencyPlugin(getContext(), ModelColumnPlugin.class)) {
            warnings.add("itfsw:插件" + this.getClass().getTypeName() + "插件需配合" + ModelColumnPlugin.class.getTypeName() + "插件使用!");
            return false;
        }

        return super.validate(warnings);
    }

    @Override
    public boolean clientGenerated(Interface interfaze, TopLevelClass topLevelClass,
                                   IntrospectedTable introspectedTable) {
        addMethodUpdateExampleSelectiveExt(interfaze, introspectedTable);
        logger.debug("itfsw(SelectiveExtensionMethodPlugin):" + interfaze.getType().getShortName() + "增加updateByExampleSelectiveExt方法。");
        addMethodUpdateByPrimaryKeySelectiveExt(interfaze, introspectedTable);
        logger.debug("itfsw(SelectiveExtensionMethodPlugin):" + interfaze.getType().getShortName() + "增加updateByPrimaryKeySelectiveExt方法。");
        return super.clientGenerated(interfaze, topLevelClass, introspectedTable);
    }

    @Override
    public boolean sqlMapDocumentGenerated(Document document, IntrospectedTable introspectedTable) {
        XmlElement parentElement = document.getRootElement();
        // 1. insertSelectiveExt
        XmlElement insertSelectiveExt  = new XmlElement(METHOD_INSERT_SELECTIVE_EXT);
        commentGenerator.addComment(insertSelectiveExt);
        parentElement.addElement(insertSelectiveExt);
        sqlMapInsertSelectiveElementGeneratedExt(insertSelectiveExt, introspectedTable);
        logger.debug("itfsw(SelectiveExtensionMethodPlugin):" + introspectedTable.getMyBatis3XmlMapperFileName() + "增加insertSelectiveExt实现方法。");


        // 2. updateByExampleSelectiveExt
        XmlElement updateByExampleSelectiveExt  = new XmlElement(METHOD_UPDATE_BY_EXAMPLE_SELECTIVE_EXT);
        commentGenerator.addComment(updateByExampleSelectiveExt);
        parentElement.addElement(updateByExampleSelectiveExt);
        sqlMapUpdateByExampleSelectiveElementGeneratedExt(updateByExampleSelectiveExt, introspectedTable);
        logger.debug("itfsw(SelectiveExtensionMethodPlugin):" + introspectedTable.getMyBatis3XmlMapperFileName() + "增加updateByExampleSelectiveExt实现方法。");

        // 3. updateByExampleSelectiveExt
        XmlElement updateByPrimaryKeySelectiveExt  = new XmlElement(METHOD_UPDATE_BY_PRIMARY_KEY_SELECTIVE_EXT);
        commentGenerator.addComment(updateByPrimaryKeySelectiveExt);
        parentElement.addElement(updateByPrimaryKeySelectiveExt);
        sqlMapUpdateByPrimaryKeySelectiveElementGeneratedExt(updateByPrimaryKeySelectiveExt, introspectedTable);
        logger.debug("itfsw(SelectiveExtensionMethodPlugin):" + introspectedTable.getMyBatis3XmlMapperFileName() + "增加updateByPrimaryKeySelectiveExt实现方法。");
        return true;
    }

    private void addMethodInsertSelectiveExt(Interface interfaze, IntrospectedTable introspectedTable) {
        Method method = new Method();

        method.setReturnType(FullyQualifiedJavaType.getIntInstance());
        method.setVisibility(JavaVisibility.PUBLIC);
        method.setName(METHOD_INSERT_SELECTIVE_EXT);

        FullyQualifiedJavaType parameterType = introspectedTable.getRules()
            .calculateAllFieldsClass();

        Set<FullyQualifiedJavaType> importedTypes = new TreeSet<FullyQualifiedJavaType>();
        importedTypes.add(parameterType);
        method.addParameter(new Parameter(parameterType, "record", "@Param(\"record\")")); //$NON-NLS-1$

        // 找出全字段对应的Model
        FullyQualifiedJavaType fullFieldModel = introspectedTable.getRules().calculateAllFieldsClass();
        // column枚举
        FullyQualifiedJavaType selectiveType = new FullyQualifiedJavaType(fullFieldModel.getShortName() + "." + ModelColumnPlugin.ENUM_NAME);
        method.addParameter(new Parameter(selectiveType, "selective", "@Param(\"selective\")", true));


        commentGenerator.addGeneralMethodComment(method, introspectedTable);
        // interface 增加方法
        FormatTools.addMethodWithBestPosition(interfaze, method);
    }

    public void addMethodUpdateExampleSelectiveExt(Interface interfaze, IntrospectedTable introspectedTable) {
        Method method = new Method();
        method.setVisibility(JavaVisibility.PUBLIC);
        method.setReturnType(FullyQualifiedJavaType.getIntInstance());
        method.setName(METHOD_UPDATE_BY_EXAMPLE_SELECTIVE_EXT);

        FullyQualifiedJavaType parameterType =
            introspectedTable.getRules().calculateAllFieldsClass();
        method.addParameter(new Parameter(parameterType,
            "record", "@Param(\"record\")")); //$NON-NLS-1$ //$NON-NLS-2$

        Set<FullyQualifiedJavaType> importedTypes = new TreeSet<FullyQualifiedJavaType>();
        importedTypes.add(parameterType);

        FullyQualifiedJavaType exampleType = new FullyQualifiedJavaType(
            introspectedTable.getExampleType());
        method.addParameter(new Parameter(exampleType,
            "example", "@Param(\"example\")")); //$NON-NLS-1$ //$NON-NLS-2$
        importedTypes.add(exampleType);

        importedTypes.add(new FullyQualifiedJavaType(
            "org.apache.ibatis.annotations.Param")); //$NON-NLS-1$


        // 找出全字段对应的Model
        FullyQualifiedJavaType fullFieldModel = introspectedTable.getRules().calculateAllFieldsClass();
        // column枚举
        FullyQualifiedJavaType selectiveType = new FullyQualifiedJavaType(fullFieldModel.getShortName() + "." + ModelColumnPlugin.ENUM_NAME);
        method.addParameter(new Parameter(selectiveType, "selective", "@Param(\"selective\")", true));


        commentGenerator.addGeneralMethodComment(method, introspectedTable);
        // interface 增加方法
        FormatTools.addMethodWithBestPosition(interfaze, method);
    }
    public void addMethodUpdateByPrimaryKeySelectiveExt(Interface interfaze, IntrospectedTable introspectedTable) {
        Set<FullyQualifiedJavaType> importedTypes = new TreeSet<FullyQualifiedJavaType>();
        FullyQualifiedJavaType parameterType;

        if (introspectedTable.getRules().generateRecordWithBLOBsClass()) {
            parameterType = new FullyQualifiedJavaType(introspectedTable
                .getRecordWithBLOBsType());
        } else {
            parameterType = new FullyQualifiedJavaType(introspectedTable
                .getBaseRecordType());
        }

        importedTypes.add(parameterType);

        Method method = new Method();
        method.setVisibility(JavaVisibility.PUBLIC);
        method.setReturnType(FullyQualifiedJavaType.getIntInstance());
        method.setName(METHOD_UPDATE_BY_PRIMARY_KEY_SELECTIVE_EXT);

        method.addParameter(new Parameter(parameterType, "record", "@Param(\"record\")"));

        // 找出全字段对应的Model
        FullyQualifiedJavaType fullFieldModel = introspectedTable.getRules().calculateAllFieldsClass();
        // column枚举
        FullyQualifiedJavaType selectiveType = new FullyQualifiedJavaType(fullFieldModel.getShortName() + "." + ModelColumnPlugin.ENUM_NAME);
        method.addParameter(new Parameter(selectiveType, "selective", "@Param(\"selective\")", true));

        commentGenerator.addGeneralMethodComment(method, introspectedTable);
        // interface 增加方法
        FormatTools.addMethodWithBestPosition(interfaze, method);
    }

    private boolean sqlMapInsertSelectiveElementGeneratedExt(XmlElement element, IntrospectedTable introspectedTable) {
        // 清空
        XmlElement answer = new XmlElement("insert");
        answer.addAttribute(new Attribute("id", METHOD_INSERT_SELECTIVE_EXT));
        answer.addAttribute(new Attribute("parameterType", "map"));

        commentGenerator.addComment(answer);

        GeneratedKey gk = introspectedTable.getGeneratedKey();
        if (gk != null) {
            IntrospectedColumn introspectedColumn = introspectedTable.getColumn(gk.getColumn());
            // if the column is null, then it's a configuration error. The
            // warning has already been reported
            if (introspectedColumn != null) {
                if (gk.isJdbcStandard()) {
                    XmlElementGeneratorTools.useGeneratedKeys(answer, introspectedTable, "record.");
                } else {
                    answer.addElement(XmlElementGeneratorTools.getSelectKey(introspectedColumn, gk, "record."));
                }
            }
        }

        StringBuilder sb = new StringBuilder();

        sb.append("insert into ");
        sb.append(introspectedTable.getFullyQualifiedTableNameAtRuntime());
        answer.addElement(new TextElement(sb.toString()));

        // columns
        answer.addElement(this.generateInsertColumnSelective(ListUtilities.removeIdentityAndGeneratedAlwaysColumns(introspectedTable.getAllColumns())));
        // values
        answer.addElement(new TextElement("values"));
        answer.addElement(this.generateInsertValuesSelective(ListUtilities.removeIdentityAndGeneratedAlwaysColumns(introspectedTable.getAllColumns())));

        XmlElementTools.replaceXmlElement(element, answer);

        return super.sqlMapInsertSelectiveElementGenerated(element, introspectedTable);
    }

    private boolean sqlMapUpdateByExampleSelectiveElementGeneratedExt(XmlElement element, IntrospectedTable introspectedTable) {
        // 清空
        XmlElement answer = new XmlElement("update");
        answer.addAttribute(new Attribute("id", METHOD_UPDATE_BY_EXAMPLE_SELECTIVE_EXT));
        answer.addAttribute(new Attribute("parameterType", "map"));

        commentGenerator.addComment(answer);

        StringBuilder sb = new StringBuilder();
        sb.append("update ");
        sb.append(introspectedTable.getAliasedFullyQualifiedTableNameAtRuntime());
        answer.addElement(new TextElement(sb.toString()));

        // selective
        answer.addElement(new TextElement("SET"));
        answer.addElement(this.generateSetsSelective(ListUtilities.removeGeneratedAlwaysColumns(introspectedTable.getAllColumns())));

        answer.addElement(XmlElementGeneratorTools.getUpdateByExampleIncludeElement(introspectedTable));

        XmlElementTools.replaceXmlElement(element, answer);

        return super.sqlMapUpdateByExampleSelectiveElementGenerated(element, introspectedTable);
    }

    private boolean sqlMapUpdateByPrimaryKeySelectiveElementGeneratedExt(XmlElement element, IntrospectedTable introspectedTable) {
        // 清空
        XmlElement answer = new XmlElement("update");
        answer.addAttribute(new Attribute("id", METHOD_UPDATE_BY_PRIMARY_KEY_SELECTIVE_EXT));
        answer.addAttribute(new Attribute("parameterType", "map"));

        commentGenerator.addComment(answer);

        StringBuilder sb = new StringBuilder();

        sb.append("update ");
        sb.append(introspectedTable.getFullyQualifiedTableNameAtRuntime());
        answer.addElement(new TextElement(sb.toString()));

        // selective
        answer.addElement(new TextElement("SET"));
        answer.addElement(this.generateSetsSelective(ListUtilities.removeGeneratedAlwaysColumns(introspectedTable.getNonPrimaryKeyColumns())));

        XmlElementGeneratorTools.generateWhereByPrimaryKeyTo(answer, introspectedTable.getPrimaryKeyColumns(), "record.");

        XmlElementTools.replaceXmlElement(element, answer);
        return super.sqlMapUpdateByPrimaryKeySelectiveElementGenerated(element, introspectedTable);
    }


    // =============================================== IUpsertPluginHook ===================================================

    /**
     * upsertSelective 方法
     * @param method
     * @param interfaze
     * @param introspectedTable
     * @return
     */
    @Override
    public boolean clientUpsertSelectiveMethodGenerated(Method method, Interface interfaze, IntrospectedTable introspectedTable) {
        // @Param("record")
        method.getParameters().get(0).addAnnotation("@Param(\"record\")");
        // column枚举
        // 找出全字段对应的Model
        FullyQualifiedJavaType fullFieldModel = introspectedTable.getRules().calculateAllFieldsClass();
        FullyQualifiedJavaType selectiveType = new FullyQualifiedJavaType(fullFieldModel.getShortName() + "." + ModelColumnPlugin.ENUM_NAME);
        method.addParameter(new Parameter(selectiveType, "selective", "@Param(\"selective\")", true));
        return true;
    }

    /**
     * upsertByExampleSelective 方法
     * @param method
     * @param interfaze
     * @param introspectedTable
     * @return
     */
    @Override
    public boolean clientUpsertByExampleSelectiveMethodGenerated(Method method, Interface interfaze, IntrospectedTable introspectedTable) {
        // column枚举
        // 找出全字段对应的Model
        FullyQualifiedJavaType fullFieldModel = introspectedTable.getRules().calculateAllFieldsClass();
        FullyQualifiedJavaType selectiveType = new FullyQualifiedJavaType(fullFieldModel.getShortName() + "." + ModelColumnPlugin.ENUM_NAME);
        method.addParameter(new Parameter(selectiveType, "selective", "@Param(\"selective\")", true));
        return true;
    }

    /**
     * upsertSelective xml
     * @param element
     * @param columns
     * @param insertColumnsEle
     * @param insertValuesEle
     * @param setsEle
     * @param introspectedTable
     * @return
     */
    @Override
    public boolean sqlMapUpsertSelectiveElementGenerated(XmlElement element, List<IntrospectedColumn> columns, XmlElement insertColumnsEle, XmlElement insertValuesEle, XmlElement setsEle, IntrospectedTable introspectedTable) {
        // parameterType
        XmlElementTools.replaceAttribute(element, new Attribute("parameterType", "map"));

        // 替换insert column
        XmlElementTools.replaceXmlElement(insertColumnsEle, this.generateInsertColumnSelective(columns));

        // 替换insert values
        XmlElementTools.replaceXmlElement(insertValuesEle, this.generateInsertValuesSelective(columns));

        // 替换update set
        XmlElementTools.replaceXmlElement(setsEle, this.generateSetsSelective(columns));

        return true;
    }

    /**
     * upsertByExampleSelective xml
     * @param element
     * @param columns
     * @param insertColumnsEle
     * @param insertValuesEle
     * @param setsEle
     * @param introspectedTable
     * @return
     */
    @Override
    public boolean sqlMapUpsertByExampleSelectiveElementGenerated(XmlElement element, List<IntrospectedColumn> columns, XmlElement insertColumnsEle, XmlElement insertValuesEle, XmlElement setsEle, IntrospectedTable introspectedTable) {

        // 替换insert column
        XmlElementTools.replaceXmlElement(insertColumnsEle, this.generateInsertColumnSelective(columns));

        // 替换insert values
        XmlElementTools.replaceXmlElement(insertValuesEle, this.generateInsertValuesSelective(columns, false));

        // 替换update set
        XmlElementTools.replaceXmlElement(setsEle, this.generateSetsSelective(columns));

        return true;
    }

    // ================================================= IOptimisticLockerPluginHook ===============================================

    @Override
    public boolean clientUpdateWithVersionByExampleSelectiveMethodGenerated(Method method, Interface interfaze, IntrospectedTable introspectedTable) {
        // column枚举,找出全字段对应的Model
        FullyQualifiedJavaType fullFieldModel = introspectedTable.getRules().calculateAllFieldsClass();
        FullyQualifiedJavaType selectiveType = new FullyQualifiedJavaType(fullFieldModel.getShortName() + "." + ModelColumnPlugin.ENUM_NAME);
        method.addParameter(new Parameter(selectiveType, "selective", "@Param(\"selective\")", true));
        return true;
    }

    @Override
    public boolean clientUpdateWithVersionByPrimaryKeySelectiveMethodGenerated(Method method, Interface interfaze, IntrospectedTable introspectedTable) {
        // column枚举,找出全字段对应的Model
        FullyQualifiedJavaType fullFieldModel = introspectedTable.getRules().calculateAllFieldsClass();
        FullyQualifiedJavaType selectiveType = new FullyQualifiedJavaType(fullFieldModel.getShortName() + "." + ModelColumnPlugin.ENUM_NAME);
        method.addParameter(new Parameter(selectiveType, "selective", "@Param(\"selective\")", true));
        return true;
    }

    @Override
    public boolean generateSetsSelectiveElement(List<IntrospectedColumn> columns, IntrospectedColumn versionColumn, XmlElement setsElement) {
        // 替换update set
        XmlElementTools.replaceXmlElement(setsElement, this.generateSetsSelective(columns, versionColumn));
        return true;
    }

    // ====================================================== 一些私有节点生成方法 =========================================================

    /**
     * insert column selective
     * @param columns
     * @return
     */
    private XmlElement generateInsertColumnSelective(List<IntrospectedColumn> columns) {
        XmlElement insertColumnsChooseEle = new XmlElement("choose");

        XmlElement insertWhenEle = new XmlElement("when");
        insertWhenEle.addAttribute(new Attribute("test", "selective != null and selective.length > 0"));
        insertColumnsChooseEle.addElement(insertWhenEle);

        XmlElement insertForeachEle = new XmlElement("foreach");
        insertForeachEle.addAttribute(new Attribute("collection", "selective"));
        insertForeachEle.addAttribute(new Attribute("item", "column"));
        insertForeachEle.addAttribute(new Attribute("open", "("));
        insertForeachEle.addAttribute(new Attribute("separator", ","));
        insertForeachEle.addAttribute(new Attribute("close", ")"));
        insertForeachEle.addElement(new TextElement("${column.escapedColumnName}"));
        insertWhenEle.addElement(insertForeachEle);

        XmlElement insertOtherwiseEle = new XmlElement("otherwise");
        insertOtherwiseEle.addElement(XmlElementGeneratorTools.generateKeysSelective(columns, "record."));
        insertColumnsChooseEle.addElement(insertOtherwiseEle);

        XmlElement insertTrimElement = new XmlElement("trim");
        insertTrimElement.addAttribute(new Attribute("prefix", "("));
        insertTrimElement.addAttribute(new Attribute("suffix", ")"));
        insertTrimElement.addAttribute(new Attribute("suffixOverrides", ","));
        insertOtherwiseEle.addElement(insertTrimElement);

        return insertColumnsChooseEle;
    }

    /**
     * insert column selective
     * @param columns
     * @return
     */
    private XmlElement generateInsertValuesSelective(List<IntrospectedColumn> columns) {
        return generateInsertValuesSelective(columns, true);
    }

    /**
     * insert column selective
     * @param columns
     * @param bracket
     * @return
     */
    private XmlElement generateInsertValuesSelective(List<IntrospectedColumn> columns, boolean bracket) {
        XmlElement insertValuesChooseEle = new XmlElement("choose");

        XmlElement valuesWhenEle = new XmlElement("when");
        valuesWhenEle.addAttribute(new Attribute("test", "selective != null and selective.length > 0"));
        insertValuesChooseEle.addElement(valuesWhenEle);

        XmlElement valuesForeachEle = new XmlElement("foreach");
        valuesForeachEle.addAttribute(new Attribute("collection", "selective"));
        valuesForeachEle.addAttribute(new Attribute("item", "column"));
        valuesForeachEle.addAttribute(new Attribute("separator", ","));
        if (bracket) {
            valuesForeachEle.addAttribute(new Attribute("open", "("));
            valuesForeachEle.addAttribute(new Attribute("close", ")"));
        }
        valuesForeachEle.addElement(new TextElement("#{record.${column.javaProperty},jdbcType=${column.jdbcType}}"));
        valuesWhenEle.addElement(valuesForeachEle);

        XmlElement valuesOtherwiseEle = new XmlElement("otherwise");
        insertValuesChooseEle.addElement(valuesOtherwiseEle);
        valuesOtherwiseEle.addElement(XmlElementGeneratorTools.generateValuesSelective(columns, "record.", bracket));

        return insertValuesChooseEle;
    }

    /**
     * sets selective
     * @param columns
     * @return
     */
    private XmlElement generateSetsSelective(List<IntrospectedColumn> columns) {
        return generateSetsSelective(columns, null);
    }

    /**
     * sets selective
     * @param columns
     * @return
     */
    private XmlElement generateSetsSelective(List<IntrospectedColumn> columns, IntrospectedColumn versionColumn) {
        XmlElement setsChooseEle = new XmlElement("choose");

        XmlElement setWhenEle = new XmlElement("when");
        setWhenEle.addAttribute(new Attribute("test", "selective != null and selective.length > 0"));
        setsChooseEle.addElement(setWhenEle);

        XmlElement setForeachEle = new XmlElement("foreach");
        setWhenEle.addElement(setForeachEle);
        setForeachEle.addAttribute(new Attribute("collection", "selective"));
        setForeachEle.addAttribute(new Attribute("item", "column"));
        setForeachEle.addAttribute(new Attribute("separator", ","));

        Element incrementEle = PluginTools.getHook(IIncrementsPluginHook.class).incrementSetsWithSelectiveEnhancedPluginElementGenerated(versionColumn);
        // 普通情况
        if (incrementEle == null && versionColumn == null) {
            setForeachEle.addElement(new TextElement("${column.escapedColumnName} = #{record.${column.javaProperty},jdbcType=${column.jdbcType}}"));
        } else if (incrementEle != null) {
            setForeachEle.addElement(incrementEle);
        } else if (versionColumn != null) {
            XmlElement ifEle = new XmlElement("if");
            ifEle.addAttribute(new Attribute("test", "column.value != '" + versionColumn.getActualColumnName() + "'.toString()"));
            ifEle.addElement(new TextElement("${column.escapedColumnName} = #{record.${column.javaProperty},jdbcType=${column.jdbcType}}"));

            setForeachEle.addElement(ifEle);
        }


        XmlElement setOtherwiseEle = new XmlElement("otherwise");
        setOtherwiseEle.addElement(XmlElementGeneratorTools.generateSetsSelective(columns, "record."));
        setsChooseEle.addElement(setOtherwiseEle);

        return setsChooseEle;
    }
}
mybatis也能方向生成代码,能方向生成实体类(po)、mapper接口和Mapper接口映射文件,能减少我们代码的工作量。详细步骤如下 1、下载mybatis生成架包工具MyBatis_Generator_1.3.1.zip,解压架包把features、plugins文件夹下的架包分别拷贝到eclipse安装目录下的features、plugins文件夹。重启eclipse就行。 解压后图片如下: Eclipse路径如图: 拷贝替换如图: 2、创建generatorConfig.xml文件,安装好mybatis 就能创建generatorConfig.xml 3、配置generatorConfig.xml配置文件,详细如下 [html] view plain copy <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd" > <generatorConfiguration> <!-- <classPathEntry location="D:\\rep\\mysql\\mysql-connector-java\\5.1.19\\mysql-connector-java-5.1.19.jar" /> --> <classPathEntry location="D:\\repo\\com\\oracle\\ojdbc14\\10.2.0.1.0\\ojdbc14-10.2.0.1.0.jar" /> <context id="DB2Tables" targetRuntime="MyBatis3"> <commentGenerator> <property name="suppressAllComments" value="true" /> <property name="suppressDate" value="true" /> </commentGenerator> <jdbcConnection driverClass="oracle.jdbc.driver.OracleDriver" connectionURL="jdbc:oracle:thin:@xxx.xxx.xxx.xxx:1521:orcl4" userId="xxx" password="xxxx" /> <javaTypeResolver> <property name="forceBigDecimals" value="false" /> <!-- 默认false,把JDBC DECIMAL 和 NUMERIC 类型解析为 Integer true,把JDBC DECIMAL 和 NUMERIC 类型解析为java.math.BigDecimal --> </javaTypeResolver> <javaModelGenerator targetPackage="com.pcmall.domain.sale.order" targetProject="pos-service/src/main/java"> <property name="enableSubPackages" value="true" /> <property name="trimStrings" value="true" /> </javaModelGenerator> <sqlMapGenerator targetPackage="mybatis.mapper.sale.order" targetProject="pos-service/src/main/resources"> <property name="enableSubPackages" value="false" /> </sqlMapGenerator> <javaClientGenerator targetPackage="com.pcmall.dao.sale.order" targetProject="pos-service/src/main/java" type="XMLMAPPER"> <property name="enableSubPackages" value="false" /> </javaClientGenerator> <table tableName="hs_zxzflx" enableSelectByExample="false" enableDeleteByExample="false" enableCountByExample="false" selectByExampleQueryId="true" enableUpdateByExample="false"> <!-- <generatedKey column="ID" sqlStatement="oracle" identity="true" /> --> </table> </context> </generatorConfiguration> 4、右击generatorConfig.xml 点击Generate MyBatis/iBATIS Artifacts 生成对应接口、接口映射文件、实体类 5、查看结果
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值