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

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

         今天主要讲解如何解决我们使用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<String> 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节点配置里面加入一个参数

<!-- 自定义XML节点 -->
<!ELEMENT javaParam (property*)>
<!ATTLIST javaParam
  baseDAO CDATA #REQUIRED
  baseService CDATA #REQUIRED
  buildType CDATA #REQUIRED
  mapperExt CDATA #REQUIRED>


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

<!--自定义XML参数配置 -->
		<javaParam baseDAO="com.test.BaseDAO" 
		baseService="com.test.BaseService" 
		buildType="1,2" mapperExt="DAO">

		</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<GeneratedJavaFile> generatedJavaFiles,
            List<GeneratedXmlFile> generatedXmlFiles, List<String> 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.最后看看我们的运行生成结果




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

目录
相关文章
|
12天前
|
Java 数据库连接 mybatis
Mybatis查询传递单个参数和传递多个参数用法
Mybatis查询传递单个参数和传递多个参数用法
27 11
|
19天前
|
SQL
自定义SQL,可以利用MyBatisPlus的Wrapper来构建复杂的Where条件,如何自定义SQL呢?利用MyBatisPlus的Wrapper来构建Wh,在mapper方法参数中用Param注
自定义SQL,可以利用MyBatisPlus的Wrapper来构建复杂的Where条件,如何自定义SQL呢?利用MyBatisPlus的Wrapper来构建Wh,在mapper方法参数中用Param注
|
28天前
|
Java 数据库连接 mybatis
mybatis参数报错Parameter ‘docId‘ not found. Available parameters are [arg1, arg0, param1, param2]
mybatis参数报错Parameter ‘docId‘ not found. Available parameters are [arg1, arg0, param1, param2]
MyBatisPlus如何根据id批量查询?Required request parameter ‘id‘ for method 解决方法是看青戈大佬MybatisPlus的教程
MyBatisPlus如何根据id批量查询?Required request parameter ‘id‘ for method 解决方法是看青戈大佬MybatisPlus的教程
|
21天前
|
Java 数据库连接 Maven
Private method ‘getVideoList()‘ is never used,mybatis必须指定Mapper文件和实体目录,在参考其他人写的代码,要认真分析别人的代码,不要丢失
Private method ‘getVideoList()‘ is never used,mybatis必须指定Mapper文件和实体目录,在参考其他人写的代码,要认真分析别人的代码,不要丢失
|
27天前
|
SQL Java 数据库连接
Mybatis如何使用mapper代理开发
Mybatis如何使用mapper代理开发
|
27天前
|
Java 数据库连接 数据库
MyBatis TypeHandler详解:原理与自定义实践
MyBatis TypeHandler详解:原理与自定义实践
|
2月前
|
算法 Java 数据库连接
Spring+MySQL+数据结构+集合,Alibaba珍藏版mybatis手写文档
Spring+MySQL+数据结构+集合,Alibaba珍藏版mybatis手写文档
|
2月前
|
Java 数据库连接 Spring
Spring 整合mybatis
Spring 整合mybatis
31 2
|
1月前
|
Java 数据库连接 mybatis
在Spring Boot应用中集成MyBatis与MyBatis-Plus
在Spring Boot应用中集成MyBatis与MyBatis-Plus
68 5