mybatis-generator扩展教程系列 -- 自定义配置参数修改DAO,Mapper文件后缀

         今天主要讲解如何解决我们使用mybatis生成器遇到的最常见问题,如何修改生成的dao,mapper文件后缀,下面我们继续使用上一篇的用例继续改造,如果本篇示例看得不太理解的可以翻看下之前的演示,下面就开始直奔主题了


1. 先增加一个参数配置看我们的文件生成后缀是什么,我们就新增个mapperExt参数写在JavaParamConfiguration.java配置对象类

package org.mybatis.generator.config;

import static org.mybatis.generator.internal.util.StringUtility.stringHasValue;
import static org.mybatis.generator.internal.util.messages.Messages.getString;

import java.util.List;

import org.mybatis.generator.api.dom.xml.Attribute;
import org.mybatis.generator.api.dom.xml.XmlElement;

/**
 * @author shadow
 */
public class JavaParamConfiguration extends TypedPropertyHolder {

	private String baseDAO; // baseDAO类路径
	private String baseService; // baseService类路径
	private String buildType; // 1.dao层 2.service层 3.control层
	private String mapperExt; // dao文件后缀配置

	public JavaParamConfiguration() {
		super();
	}

	public String getBaseDAO() {
		return baseDAO;
	}

	public void setBaseDAO(String baseDAO) {
		this.baseDAO = baseDAO;
	}

	public String getBaseService() {
		return baseService;
	}

	public void setBaseService(String baseService) {
		this.baseService = baseService;
	}

	public String getBuildType() {
		return buildType;
	}

	public void setBuildType(String buildType) {
		this.buildType = buildType;
	}

	public String getMapperExt() {
		return mapperExt;
	}

	public void setMapperExt(String mapperExt) {
		this.mapperExt = mapperExt;
	}

	public XmlElement toXmlElement() {
		XmlElement answer = new XmlElement("javaParam"); //$NON-NLS-1$

		if (baseDAO != null) {
			answer.addAttribute(new Attribute("baseDAO", baseDAO)); //$NON-NLS-1$
		}

		if (baseService != null) {
			answer.addAttribute(new Attribute("baseService", baseService)); //$NON-NLS-1$
		}

		if (buildType != null) {
			answer.addAttribute(new Attribute("buildType", buildType)); //$NON-NLS-1$
		}
		
		if (mapperExt != null) {
			answer.addAttribute(new Attribute("mapperExt", mapperExt)); //$NON-NLS-1$
		}

		addPropertyXmlElements(answer);

		return answer;
	}

	public void validate(List errors, String contextId) {

		if (!stringHasValue(baseDAO)) {
			errors.add(getString("ValidationError.12", //$NON-NLS-1$
					"JavaParamConfiguration", contextId)); //$NON-NLS-1$
		}

		if (!stringHasValue(baseService)) {
			errors.add(getString("ValidationError.13", //$NON-NLS-1$
					"JavaParamConfiguration", contextId)); //$NON-NLS-1$
		}

		if (!stringHasValue(buildType)) {
			errors.add(getString("ValidationError.14", //$NON-NLS-1$
					"JavaParamConfiguration", contextId)); //$NON-NLS-1$
		}

	}
}


2.修改mybatis-generator-config_1_0.dtd文件,javaParam节点配置里面加入一个参数




3.修改generatorConfig.xml文件,在javaParam节点加入我们的参数值


		

		


修改填充数据对象代码MyBatisGeneratorConfigurationParser.java

private void parseJavaParam(Context context, Node node) {
        JavaParamConfiguration javaParamConfiguration = new JavaParamConfiguration();

        context.setJavaParamConfiguration(javaParamConfiguration);

        Properties attributes = parseAttributes(node);
        String baseDAO = attributes.getProperty("baseDAO"); //$NON-NLS-1$
        String baseService = attributes.getProperty("baseService"); //$NON-NLS-1$
        String buildType = attributes.getProperty("buildType"); //$NON-NLS-1$
        String mapperExt = attributes.getProperty("mapperExt"); // 增加自定义参数填充

        javaParamConfiguration.setBaseDAO(baseDAO);
        javaParamConfiguration.setBaseService(baseService);
        javaParamConfiguration.setBuildType(buildType);
        javaParamConfiguration.setMapperExt(mapperExt);

        NodeList nodeList = node.getChildNodes();
        for (int i = 0; i < nodeList.getLength(); i++) {
            Node childNode = nodeList.item(i);

            if (childNode.getNodeType() != Node.ELEMENT_NODE) {
                continue;
            }

            if ("property".equals(childNode.getNodeName())) { //$NON-NLS-1$
                parseProperty(javaParamConfiguration, childNode);
            }
        }
    }



4.我们来看看生成文件的主要实现类IntrospectedTableMyBatis3Impl.java下面这段方法,我们可以看到第729行introspectedTable.initialize();初始化配置文件

/**
     * Generate files.
     *
     * @param callback
     *            the callback
     * @param generatedJavaFiles
     *            the generated java files
     * @param generatedXmlFiles
     *            the generated xml files
     * @param warnings
     *            the warnings
     * @throws InterruptedException
     *             the interrupted exception
     */
    public void generateFiles(ProgressCallback callback,
            List generatedJavaFiles,
            List generatedXmlFiles, List warnings)
            throws InterruptedException {

        pluginAggregator = new PluginAggregator();
        for (PluginConfiguration pluginConfiguration : pluginConfigurations) {
            Plugin plugin = ObjectFactory.createPlugin(this,
                    pluginConfiguration);
            if (plugin.validate(warnings)) {
                pluginAggregator.addPlugin(plugin);
            } else {
                warnings.add(getString("Warning.24", //$NON-NLS-1$
                        pluginConfiguration.getConfigurationType(), id));
            }
        }

        if (introspectedTables != null) {
            for (IntrospectedTable introspectedTable : introspectedTables) {
                callback.checkCancel();

                introspectedTable.initialize();
                introspectedTable.calculateGenerators(warnings, callback);
                generatedJavaFiles.addAll(introspectedTable
                        .getGeneratedJavaFiles());
                generatedXmlFiles.addAll(introspectedTable
                        .getGeneratedXmlFiles());

                generatedJavaFiles.addAll(pluginAggregator
                        .contextGenerateAdditionalJavaFiles(introspectedTable));
                generatedXmlFiles.addAll(pluginAggregator
                        .contextGenerateAdditionalXmlFiles(introspectedTable));
            }
        }

        generatedJavaFiles.addAll(pluginAggregator
                .contextGenerateAdditionalJavaFiles());
        generatedXmlFiles.addAll(pluginAggregator
                .contextGenerateAdditionalXmlFiles());
    }


5.我们继续深入进去看IntrospectedTable.java的initialize()方法实现

public void initialize() {
        calculateJavaClientAttributes();
        calculateModelAttributes();
        calculateXmlAttributes();

        if (tableConfiguration.getModelType() == ModelType.HIERARCHICAL) {
            rules = new HierarchicalModelRules(this);
        } else if (tableConfiguration.getModelType() == ModelType.FLAT) {
            rules = new FlatModelRules(this);
        } else {
            rules = new ConditionalModelRules(this);
        }

        context.getPlugins().initialized(this);
    }

6.可以看到calculateJavaClientAttributes,calculateModelAttributes,calculateXmlAttributes三行代码应该就是初始化实现代码

我们把calculateJavaClientAttributes方法1345行代码,修改成如下

protected void calculateJavaClientAttributes() {
        if (context.getJavaClientGeneratorConfiguration() == null) {
            return;
        }

        StringBuilder sb = new StringBuilder();
        sb.append(calculateJavaClientImplementationPackage());
        sb.append('.');
        sb.append(fullyQualifiedTable.getDomainObjectName());
        sb.append("DAOImpl"); //$NON-NLS-1$
        setDAOImplementationType(sb.toString());

        sb.setLength(0);
        sb.append(calculateJavaClientInterfacePackage());
        sb.append('.');
        sb.append(fullyQualifiedTable.getDomainObjectName());
        sb.append("DAO"); //$NON-NLS-1$
        setDAOInterfaceType(sb.toString());

        sb.setLength(0);
        sb.append(calculateJavaClientInterfacePackage());
        sb.append('.');
        if (stringHasValue(tableConfiguration.getMapperName())) {
            sb.append(tableConfiguration.getMapperName());
        } else {
            sb.append(fullyQualifiedTable.getDomainObjectName());
            // sb.append("Mapper"); //$NON-NLS-1$
            sb.append(context.getJavaParamConfiguration().getMapperExt()); // 修改自定义后缀名称
        }
        setMyBatis3JavaMapperType(sb.toString());

        sb.setLength(0);
        sb.append(calculateJavaClientInterfacePackage());
        sb.append('.');
        if (stringHasValue(tableConfiguration.getSqlProviderName())) {
            sb.append(tableConfiguration.getSqlProviderName());
        } else {
            sb.append(fullyQualifiedTable.getDomainObjectName());
            sb.append("SqlProvider"); //$NON-NLS-1$
        }
        setMyBatis3SqlProviderType(sb.toString());
    }


7.最后看看我们的运行生成结果




最后小结,示例是沿用之前的讲解用例,所以如果有的地方没看明白可以翻看下我之前的讲解教程,谢谢大家的支持

你可能感兴趣的:(mybatis,java)