SpringBoot中generator整合lombok和添加注释

一、研究问题

本文分享使用Mybatis的逆向工程generator的时候,将生成的实体改为lombok形式,并且在成员变量上添加数据库中的字段描述(中文的描述哦)。
本次环境是基于SpringBoot和MySQL,阅读前提是你先会使用原生的generator工具,如果你的环境是普通maven或其它环境也可以阅读,换汤不换药的。
这里先看下图效果:一张数据库表,student库下的class,如果是原生的generator工具生成的实体中会有很多set,get方法,而且成员变量上没有描述或是英文描述,而下面是已经修改过的效果。
SpringBoot中generator整合lombok和添加注释_第1张图片
SpringBoot中generator整合lombok和添加注释_第2张图片

二、整合lombok

逆向工程是通过使用工具生成的代码,所以我们就修改他的工具源码,先解决第一个问题,将生成的实体类换成lombok形式。

首先需要准备两个工程

一个是原生的generator工程,测试使用它可以生成原来有set,get的实体,没有问题。下文称它为大工程,如何搭建原生generator的就不介绍了。
另一个是一个辅助工程,使用它来修改源码,不会添加在项目中。下方称它为小工程

2.1 创建小工程并修改源码

2.1.1 maven依赖

依赖如下,必要引入的有注释说明,其它不用较劲,这个小工程修改完源码就可以删除了的。


        
            org.springframework.boot
            spring-boot-starter
        

        
            org.projectlombok
            lombok
            true
        
        
            org.springframework.boot
            spring-boot-starter-test
            test
            
                
                    org.junit.vintage
                    junit-vintage-engine
                
            
        
        
        
            org.mybatis.generator
            mybatis-generator-core
            1.3.7
        
    

2.1.2 修改插件Plugin

在小工程中,创建包org.mybatis.generator,然后在包下新建类继承PluginAdapter。包名不可以修改,类名可以修改。下面我自己定义的是LombokPlugin,可以直接复制以下代码。
SpringBoot中generator整合lombok和添加注释_第3张图片

package org.mybatis.generator.plugins;

import org.mybatis.generator.api.IntrospectedColumn;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.PluginAdapter;
import org.mybatis.generator.api.dom.java.Interface;
import org.mybatis.generator.api.dom.java.Method;
import org.mybatis.generator.api.dom.java.TopLevelClass;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

public class LombokPlugin extends PluginAdapter {
    public LombokPlugin() {
    }

    public boolean validate(List list) {
        return true;
    }

    public boolean modelBaseRecordClassGenerated(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
        topLevelClass.addImportedType("lombok.Data");
        topLevelClass.addAnnotation("@Data");
        //topLevelClass.addImportedType("lombok.Getter");
        //topLevelClass.addImportedType("lombok.Setter");
        //topLevelClass.addImportedType("lombok.ToString");
        //topLevelClass.addAnnotation("@Getter");
        //topLevelClass.addAnnotation("@Setter");
        //topLevelClass.addAnnotation("@ToString");
        topLevelClass.addJavaDocLine("/**");
        topLevelClass.addJavaDocLine("* Created by Mybatis Generator " + this.date2Str(new Date()));
        topLevelClass.addJavaDocLine("*/");
        return true;
    }

    public boolean clientGenerated(Interface interfaze, TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
        interfaze.addJavaDocLine("/**");
        interfaze.addJavaDocLine("* Created by Mybatis Generator " + this.date2Str(new Date()));
        interfaze.addJavaDocLine("*/");
        return true;
    }

    public boolean modelSetterMethodGenerated(Method method, TopLevelClass topLevelClass, IntrospectedColumn introspectedColumn, IntrospectedTable introspectedTable, ModelClassType modelClassType) {
        return false;
    }

    public boolean modelGetterMethodGenerated(Method method, TopLevelClass topLevelClass, IntrospectedColumn introspectedColumn, IntrospectedTable introspectedTable, ModelClassType modelClassType) {
        return false;
    }

    private String date2Str(Date date) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
        return sdf.format(date);
    }
}

2.1.3 将修改完的插件编译成.class文件

先clean一下,清除缓存。
SpringBoot中generator整合lombok和添加注释_第4张图片
然后点一下小工程修改的代码,让光标在修改了插件的那个类里闪烁。进行下一步。
SpringBoot中generator整合lombok和添加注释_第5张图片

2.2 大工程修改

maven中必须引入mybatis-generator-core,因为你一会需要把这个.class替换。下面pom文件不用全复制,只需要在你的原生generator,也就是大工程中复制mybatis-generator-core和lombok即可,注意自己的mybatis-generator-core版本,我的是1.3.7。


        
            org.springframework.boot
            spring-boot-starter
        

        
            org.projectlombok
            lombok
            true
        
        
            org.springframework.boot
            spring-boot-starter-test
            test
            
                
                    org.junit.vintage
                    junit-vintage-engine
                
            
        
        
        
            org.mybatis.generator
            mybatis-generator-core
            1.3.7
        
    

    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
            
                org.mybatis.generator
                mybatis-generator-maven-plugin
                1.3.7
                
                    
                        mybatis-generator
                        deploy
                        
                            generate
                        
                    
                
                
                    
                    src/main/resources/mybatis-generator/generatorConfig.xml
                    true
                    true
                
                
                    
                        mysql
                        mysql-connector-java
                        8.0.17
                    
                
            
        
    

2.3 将2.1.3生成的.class替换

将自己生成的.class替换maven仓库中的插件。
在本地找到你生成的.class文件,ctrl+c复制
在这里插入图片描述
找到maven仓库的mybatis-generator-core,如下
SpringBoot中generator整合lombok和添加注释_第6张图片
SpringBoot中generator整合lombok和添加注释_第7张图片

2.4 最后修改一下大工程的generatorConfig.xml

context标签中添加你复制过来的插件

  

SpringBoot中generator整合lombok和添加注释_第8张图片

2.5 测试

然后启动逆向生成,查看实体
SpringBoot中generator整合lombok和添加注释_第9张图片
SpringBoot中generator整合lombok和添加注释_第10张图片

三、添加中文注释

3.1 小工程修改源代码

又回到小工程中修改源注释的源代码。在org.mybatis.generator.internal包下新建DefaultCommentGenerator实现CommentGenerator接口,包和类都不可以修改,可以直接复制以下代码。
SpringBoot中generator整合lombok和添加注释_第11张图片

package org.mybatis.generator.internal;

import org.mybatis.generator.api.CommentGenerator;
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.XmlElement;
import org.mybatis.generator.config.MergeConstants;
import org.mybatis.generator.config.PropertyRegistry;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;
import java.util.Set;

import static org.mybatis.generator.internal.util.StringUtility.isTrue;

public class DefaultCommentGenerator implements CommentGenerator {
    private Properties properties;
    private Properties systemPro;
    private boolean suppressDate;
    private boolean suppressAllComments;
    private String currentDateStr;

    public DefaultCommentGenerator() {
        super();
        properties = new Properties();
        systemPro = System.getProperties();
        suppressDate = false;
        suppressAllComments = false;
        currentDateStr = (new SimpleDateFormat("yyyy-MM-dd")).format(new Date());
    }

    @Override
    public void addJavaFileComment(CompilationUnit compilationUnit) {
        // add no file level comments by default
        return;
    }

    /**
     * Adds a suitable comment to warn users that the element was generated, and
     * when it was generated.
     */
    @Override
    public void addComment(XmlElement xmlElement) {
        return;
    }

    @Override
    public void addRootComment(XmlElement rootElement) {
        // add no document level comments by default
        return;
    }

    @Override
    public void addGeneralMethodAnnotation(Method method, IntrospectedTable introspectedTable,
                                           Set set) {

    }

    @Override
    public void addGeneralMethodAnnotation(Method method, IntrospectedTable introspectedTable, IntrospectedColumn introspectedColumn, Set set) {

    }

    @Override
    public void addFieldAnnotation(Field field, IntrospectedTable introspectedTable, Set set) {

    }

    @Override
    public void addFieldAnnotation(Field field, IntrospectedTable introspectedTable, IntrospectedColumn introspectedColumn, Set set) {

    }

    @Override
    public void addClassAnnotation(InnerClass innerClass, IntrospectedTable introspectedTable, Set set) {

    }

    @Override
    public void addConfigurationProperties(Properties properties) {
        this.properties.putAll(properties);

        suppressDate = isTrue(properties.getProperty(PropertyRegistry.COMMENT_GENERATOR_SUPPRESS_DATE));

        suppressAllComments = isTrue(properties.getProperty(PropertyRegistry.COMMENT_GENERATOR_SUPPRESS_ALL_COMMENTS));
    }

    /**
     * This method adds the custom javadoc tag for. You may do nothing if you do
     * not wish to include the Javadoc tag - however, if you do not include the
     * Javadoc tag then the Java merge capability of the eclipse plugin will
     * break.
     *
     * @param javaElement the java element
     */
    protected void addJavadocTag(JavaElement javaElement, boolean markAsDoNotDelete) {
        javaElement.addJavaDocLine(" *");
        StringBuilder sb = new StringBuilder();
        sb.append(" * ");
        sb.append(MergeConstants.NEW_ELEMENT_TAG);
        if (markAsDoNotDelete) {
            sb.append(" do_not_delete_during_merge");
        }
        String s = getDateString();
        if (s != null) {
            sb.append(' ');
            sb.append(s);
        }
        javaElement.addJavaDocLine(sb.toString());
    }

    /**
     * This method returns a formated date string to include in the Javadoc tag
     * and XML comments. You may return null if you do not want the date in
     * these documentation elements.
     *
     * @return a string representing the current timestamp, or null
     */
    protected String getDateString() {
        String result = null;
        if (!suppressDate) {
            result = currentDateStr;
        }
        return result;
    }

    @Override
    public void addClassComment(InnerClass innerClass, IntrospectedTable introspectedTable) {
        if (suppressAllComments) {
            return;
        }
        StringBuilder sb = new StringBuilder();
        innerClass.addJavaDocLine("/**");
        sb.append(" * ");
        sb.append(introspectedTable.getFullyQualifiedTable());
        sb.append(" ");
        sb.append(getDateString());
        innerClass.addJavaDocLine(sb.toString());
        innerClass.addJavaDocLine(" */");
    }

    @Override
    public void addEnumComment(InnerEnum innerEnum, IntrospectedTable introspectedTable) {
        if (suppressAllComments) {
            return;
        }

        StringBuilder sb = new StringBuilder();

        innerEnum.addJavaDocLine("/**");
        //      addJavadocTag(innerEnum, false);
        sb.append(" * ");
        sb.append(introspectedTable.getFullyQualifiedTable());
        innerEnum.addJavaDocLine(sb.toString());
        innerEnum.addJavaDocLine(" */");
    }

    @Override
    public void addFieldComment(Field field, IntrospectedTable introspectedTable,
                                IntrospectedColumn introspectedColumn) {
        if (suppressAllComments) {
            return;
        }
        if (introspectedColumn.getRemarks() != null && !introspectedColumn.getRemarks().trim().isEmpty()) {
            StringBuilder sb = new StringBuilder();

            field.addJavaDocLine("/**");
            sb.append(" * ");
            sb.append(introspectedColumn.getRemarks());
            field.addJavaDocLine(sb.toString());

            //      addJavadocTag(field, false);

            field.addJavaDocLine(" */");
        }
    }

    @Override
    public void addFieldComment(Field field, IntrospectedTable introspectedTable) {
        if (suppressAllComments) {
            return;
        }

        StringBuilder sb = new StringBuilder();

        field.addJavaDocLine("/**");
        sb.append(" * ");
        sb.append(introspectedTable.getFullyQualifiedTable());
        field.addJavaDocLine(sb.toString());
        field.addJavaDocLine(" */");
    }

    @Override
    public void addModelClassComment(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {

    }

    @Override
    public void addGeneralMethodComment(Method method, IntrospectedTable introspectedTable) {
        if (suppressAllComments) {
            return;
        }
        //      method.addJavaDocLine("/**");
        //      addJavadocTag(method, false);
        //      method.addJavaDocLine(" */");
    }

    @Override
    public void addGetterComment(Method method, IntrospectedTable introspectedTable,
                                 IntrospectedColumn introspectedColumn) {
        if (suppressAllComments) {
            return;
        }

        method.addJavaDocLine("/**");

        StringBuilder sb = new StringBuilder();
        sb.append(" * ");
        sb.append(introspectedColumn.getRemarks());
        method.addJavaDocLine(sb.toString());

        sb.setLength(0);
        sb.append(" * @return ");
        sb.append(introspectedColumn.getActualColumnName());
        sb.append(" ");
        sb.append(introspectedColumn.getRemarks());
        method.addJavaDocLine(sb.toString());

        //      addJavadocTag(method, false);

        method.addJavaDocLine(" */");
    }

    @Override
    public void addSetterComment(Method method, IntrospectedTable introspectedTable,
                                 IntrospectedColumn introspectedColumn) {
        if (suppressAllComments) {
            return;
        }


        method.addJavaDocLine("/**");
        StringBuilder sb = new StringBuilder();
        sb.append(" * ");
        sb.append(introspectedColumn.getRemarks());
        method.addJavaDocLine(sb.toString());

        Parameter parm = method.getParameters().get(0);
        sb.setLength(0);
        sb.append(" * @param ");
        sb.append(parm.getName());
        sb.append(" ");
        sb.append(introspectedColumn.getRemarks());
        method.addJavaDocLine(sb.toString());

        //      addJavadocTag(method, false);

        method.addJavaDocLine(" */");
    }

    @Override
    public void addClassComment(InnerClass innerClass, IntrospectedTable introspectedTable, boolean markAsDoNotDelete) {
        if (suppressAllComments) {
            return;
        }

        StringBuilder sb = new StringBuilder();

        innerClass.addJavaDocLine("/**");
        sb.append(" * ");
        sb.append(introspectedTable.getFullyQualifiedTable());
        innerClass.addJavaDocLine(sb.toString());

        sb.setLength(0);
        sb.append(" * @author ");
        sb.append(systemPro.getProperty("user.name"));
        sb.append(" ");
        sb.append(currentDateStr);

        //      addJavadocTag(innerClass, markAsDoNotDelete);

        innerClass.addJavaDocLine(" */");
    }

}

3.2 同样将它编译成.class文件

先clean,清空target。
SpringBoot中generator整合lombok和添加注释_第12张图片
SpringBoot中generator整合lombok和添加注释_第13张图片

3.3 替换掉maven仓库中的.class

同样找到你编译的.class文件,ctrl+c复制
在这里插入图片描述
找到maven的位置
SpringBoot中generator整合lombok和添加注释_第14张图片
使用压缩文件打开,ctrl+v粘贴,如果提示是否要替换,点击确定,全部替换。
SpringBoot中generator整合lombok和添加注释_第15张图片

3.4 确保大工程中开启注释

generatorConfig.xml配置文件开启注释
SpringBoot中generator整合lombok和添加注释_第16张图片

3.5 启动逆向工程测试

SpringBoot中generator整合lombok和添加注释_第17张图片
生成实体类
SpringBoot中generator整合lombok和添加注释_第18张图片

你可能感兴趣的:(java)