mybatis generator 扩展--自定义生成类

背景

随着越来越多的增删改查和当前固定的开发模式,所以很多代码已经可以自动的进行生成,刚好感觉mbg这个工具很好使用,想着可以不可以直接使用它进行增删改查基本的代码的生成呢?
后面经过搜索,发现了一些扩展点

扩展点

生成自定义的类
Plugin.java

 /**
     * 用于生成针对每一张表自的额外定义java文件
     * 
     * @param introspectedTable
     *            The class containing information about the table as
     *            introspected from the database
     * @return a List of GeneratedJavaFiles - these files will be saved
     *         with the other files from this run.
     */
List contextGenerateAdditionalJavaFiles

使用时机
MybatisGenerator# generate方法调用–> Context#generateFiles

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) {
                // ....
                // 在这里进行调用所有plugin的这个方法
                generatedJavaFiles.addAll(pluginAggregator
                        .contextGenerateAdditionalJavaFiles(introspectedTable));
                // 额外的xml文件
                generatedXmlFiles.addAll(pluginAggregator
                        .contextGenerateAdditionalXmlFiles(introspectedTable));
            }
        }

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

示例

public class FidCustomJavaFilePlugin extends PluginAdapter {
    @Override
    public boolean validate(List warnings) {
        return true;
    }

    /**
     * 生成额外java文件
     */
    @Override
    public List contextGenerateAdditionalJavaFiles(IntrospectedTable introspectedTable) {

        Context context = introspectedTable.getContext();

        String basePackage = context.getProperty("baseJavaPackage");
        String apiProject = context.getProperty("apiProject");
        List list = new ArrayList<>();

        List addDTOs = addDTOs(introspectedTable, basePackage);

        addDTOs.forEach(unit -> list.add(
                new GeneratedJavaFile(unit, apiProject, this.context.getProperty("javaFileEncoding"), this.context.getJavaFormatter())
        ));

        return list;
    }

    private List addDTOs(IntrospectedTable introspectedTable,  String basePackage) {
        CompilationUnit reqUnit = generateReqUnit(introspectedTable, basePackage);
        CompilationUnit respUnit = generateRespUnit(introspectedTable, basePackage);
        return Arrays.asList(reqUnit, respUnit);
    }

    private CompilationUnit generateReqUnit(IntrospectedTable introspectedTable,  String basePackage) {
        String entityClazzType = introspectedTable.getBaseRecordType();
        String destPackage = basePackage + ".dto.req";

        String domainObjectName = introspectedTable.getFullyQualifiedTable().getDomainObjectName();

        StringBuilder builder = new StringBuilder();

        FullyQualifiedJavaType superClassType = new FullyQualifiedJavaType(
                builder.append("BaseReq<")
                        .append(entityClazzType)
                        .append(">").toString()
        );

        TopLevelClass dto = new TopLevelClass(
                builder.delete(0, builder.length())
                        .append(destPackage)
                        .append(".")
                        .append(domainObjectName)
                        .append("Req")
                        .toString()
        );

        dto.setSuperClass(superClassType);
        dto.setVisibility(JavaVisibility.PUBLIC);

        FullyQualifiedJavaType baseReqInstance = FullyQualifiedJavaTypeProxyFactory.getBaseReqInstance();
        FullyQualifiedJavaType modelJavaType = new FullyQualifiedJavaType(entityClazzType);
        dto.addImportedType(baseReqInstance);
        dto.addImportedType(modelJavaType);
        dto.addJavaDocLine("/**\n" +
                " * " + getDomainName(introspectedTable) + " DTO\n" +
                " *\n" +
                " * @author " + getCurUser() + " 2019/1/8 Create 1.0  
\n" + " * @version 1.0\n" + " */"); return dto; } private String getDomainName(IntrospectedTable introspectedTable) { return introspectedTable.getRemarks() == null ? introspectedTable.getFullyQualifiedTable().getDomainObjectName() : introspectedTable.getRemarks(); } private CompilationUnit generateRespUnit(IntrospectedTable introspectedTable, String basePackage) { String entityClazzType = introspectedTable.getBaseRecordType(); String destPackage = basePackage + ".dto.resp"; String domainObjectName = introspectedTable.getFullyQualifiedTable().getDomainObjectName(); StringBuilder builder = new StringBuilder(); FullyQualifiedJavaType superClassType = new FullyQualifiedJavaType( builder.append("BaseResp<") .append(entityClazzType) .append(">").toString() ); TopLevelClass dto = new TopLevelClass( builder.delete(0, builder.length()) .append(destPackage) .append(".") .append(domainObjectName) .append("Resp") .toString() ); dto.setSuperClass(superClassType); dto.setVisibility(JavaVisibility.PUBLIC); FullyQualifiedJavaType baseReqInstance = FullyQualifiedJavaTypeProxyFactory.getBaseRespInstance(); FullyQualifiedJavaType modelJavaType = new FullyQualifiedJavaType(entityClazzType); dto.addImportedType(baseReqInstance); dto.addImportedType(modelJavaType); dto.addJavaDocLine("/**\n" + " * " + getDomainName(introspectedTable) + " DTO\n" + " *\n" + " * @author " + getCurUser() + " " + getCurDate() + " Create 1.0
\n" + " * @version 1.0\n" + " */"); return dto; } private String getCurDate() { return DateFormatUtils.format(new Date(), "yyyy/MM/dd"); } private static String getCurUser() { return System.getProperty("user.name"); } }

参考资料

https://www.jianshu.com/p/b6d981b25409 解释了一些扩展点
https://www.jianshu.com/p/ff7d697ba1f8 比较详细,但是后面的我认为过于冗余

你可能感兴趣的:(mybatis)