美文网首页
Mybatis Generator 自定义注释

Mybatis Generator 自定义注释

作者: 一只弱狗 | 来源:发表于2019-10-09 18:07 被阅读0次

    Mybatis Generator 自定义注释

    1.mybatis generator使用

    1.1. 阅读官网文档 ,导入maven plugin

    <plugin>
        <groupId>org.mybatis.generator</groupId>
        <artifactId>mybatis-generator-maven-plugin</artifactId>
        <version>1.3.7</version>
        <executions>
            <execution>
                <id>Generate MyBatis Artifacts</id>
                <goals>
                    <goal>generate</goal>
                </goals>
            </execution>
        </executions>
        <dependencies>
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>8.0.17</version>
            </dependency>
        </dependencies>
    </plugin>
    

    1.2. 在src/main/resources目录下创建generatorConfig.xml配置文件

    文件模板在官网有提供

    <?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>
    
        <context id="MysqlTables" targetRuntime="MyBatis3">
            <!--解决读取数据库中的comments中文乱码-->
            <property name="javaFileEncoding" value="UTF-8"/>
            <!--分页-->
            <plugin type="org.mybatis.generator.plugins.RowBoundsPlugin"/>
            <!--注释:课可通过type自动配置-->
            <commentGenerator type="cn.edu.nwafu.ssr.community.MyCommentGenerator">
                <property name="addRemarkComments" value="true"/>
            </commentGenerator>
            <!--jdbcConnection: 数据库连接的属性-->
            <jdbcConnection driverClass="com.mysql.jdbc.Driver"
                            connectionURL="jdbc:mysql://localhost:3306/blog_community?serverTimezone=UTC"
                            userId="root"
                            password="123456">
            </jdbcConnection>
    
            <javaTypeResolver>
                <property name="forceBigDecimals" value="false"/>
            </javaTypeResolver>
            <!--javaModelGenerator: Java模型生成器的属性 此元素是<context>元素的必需子元素。-->
            <!--enableSubPackages: value为true时,包不存在会自动创建-->
            <javaModelGenerator targetPackage="cn.edu.nwafu.ssr.community.model" targetProject="src\main\java">
                <property name="enableSubPackages" value="true"/>
                <property name="trimStrings" value="true"/>
            </javaModelGenerator>
    
            <!--Mapper.xml生成-->
            <sqlMapGenerator targetPackage="cn.edu.nwafu.ssr.community.xml" targetProject="src\main\resources">
                <property name="enableSubPackages" value="true"/>
            </sqlMapGenerator>
    
            <!--XXXMapper.java生成-->
            <javaClientGenerator type="XMLMAPPER" targetPackage="cn.edu.nwafu.ssr.community.mapper"
                                 targetProject="src\main\java">
                <property name="enableSubPackages" value="true"/>
            </javaClientGenerator>
    
            <!--  useActualColumnNames:如果为true,则MBG将使用从数据库元数据返回的列名作为生成的域对象的属性。
                                       如果为false(默认),则MBG将尝试以驼峰式表示返回的名称。
                                       默认值为false。-->
            <table schema="DB2ADMIN" tableName="tb_user" domainObjectName="User">
                <!--<property name="useActualColumnNames" value="true"/>-->
            </table>
    
        </context>
    </generatorConfiguration>
    

    1.3. 使用一下命令运行创建

    mvn -Dmybatis.generator.overwrite=true mybatis-generator:generate

    注意:使用的mysql驱动如果很新,需要在url中加入?serverTimezone=UTC,即

            <!--jdbcConnection: 数据库连接的属性-->
            <jdbcConnection driverClass="com.mysql.jdbc.Driver"
                            connectionURL="jdbc:mysql://localhost:3306/blog_community?serverTimezone=UTC"
                            userId="root"
                            password="123456">
            </jdbcConnection>
    

    否则会执行不了,会ERROR

    [ERROR] Failed to execute goal org.mybatis.generator:mybatis-generator-maven-plugin:1.3.7:generate (default-cli) on project blog_community: The
    server time zone value '?й???????' is unrecognized or represents more than one time zone. You must configure either the server or JDBC driver (
    via the serverTimezone configuration property) to use a more specifc time zone value if you want to utilize time zone support. -> [Help 1]
    [ERROR]
    [ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
    [ERROR] Re-run Maven using the -X switch to enable full debug logging.
    [ERROR]
    [ERROR] For more information about the errors and possible solutions, please read the following articles:
    [ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException
    

    1.4. 在springboot启动类 XXXApplication中添加注解

    @MapperScan(basePackages = "test.dao") //包为mapper所在的包 
    

    1.5. 上边@MapperScan注解,只是让springboot知道了Mapper.java文件的位置,但是不知道Mapper.xml文件的位置,此时需要在application.properties文件中配置

    ##mybatis配置 
    ##mybatis.mapper-locations:mapper.xml文件的位置 
    ##mybatis.type-aliases-package:实体类所在的包 
    mybatis.mapper-locations=classpath*:/test/**/*Mapper.xml
    mybatis.type-aliases-package=test.model  
    

    1.6. 官方文档

    1.6.1. mybatis generator

    1.6.2. spring-boot-starter

    1.7.可实现CommentGenerator 类,从而自动配置添加的注释

    1.7.1. 实现CommentGenerator 类

    package cn.edu.nwafu.ssr.community;
    
    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.internal.util.StringUtility;
    
    import java.text.SimpleDateFormat;
    import java.util.Date;
    import java.util.List;
    import java.util.Properties;
    import java.util.Set;
    
    
    /**
     * @author shensr
     * @version V1.0
     * @description mybatis generator自定义生成注释插件类
     * @create 2019/10/4
     **/
    public class MyCommentGenerator implements CommentGenerator {
    
        private Properties properties = new Properties();
        /**
         * 抑制日期  默认false:不抑制
         */
        private boolean suppressDate = false;
        /**
         * 抑制注释 默认false:不抑制
         */
        private boolean suppressAllComments = false;
    
        /**
         * 显示数据库comments 默认false:不显示
         */
        private boolean addRemarkComments = false;
        /**
         * 日期格式
         */
        private SimpleDateFormat dateFormat;
    
        public MyCommentGenerator() {
            super();
            dateFormat = new SimpleDateFormat("yyyy/MM/dd");
        }
    
    
        /**
         * 读取配置文件
         *
         * @param properties
         */
        @Override
        public void addConfigurationProperties(Properties properties) {
            this.properties.putAll(properties);
            this.suppressDate = StringUtility.isTrue(properties.getProperty("suppressDate"));
            this.suppressAllComments = StringUtility.isTrue(properties.getProperty("suppressAllComments"));
            this.addRemarkComments = StringUtility.isTrue(properties.getProperty("addRemarkComments"));
            String dateFormatString = properties.getProperty("dateFormat");
            if (StringUtility.stringHasValue(dateFormatString)) {
                this.dateFormat = new SimpleDateFormat(dateFormatString);
            }
    
        }
    
        /**
         * 日期格式化
         *
         * @return 格式化后的日期
         */
        protected String getDateString() {
            if (this.suppressDate) {
                return null;
            } else {
                return this.dateFormat != null ? this.dateFormat.format(new Date()) : (new Date()).toString();
            }
        }
    
        /**
         * 创建的数据表对应的类添加的注释
         *
         * @param topLevelClass
         * @param introspectedTable
         */
        @Override
        public void addModelClassComment(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
            if (!this.suppressAllComments) {
                topLevelClass.addJavaDocLine("/**");
                topLevelClass.addJavaDocLine(" * @author shensr");
                topLevelClass.addJavaDocLine(" * @version V1.0 ");
                topLevelClass.addJavaDocLine(" * @description MyBatis Generator 自动创建,对应数据表为:" + introspectedTable.getFullyQualifiedTable());
                topLevelClass.addJavaDocLine(" * @create " + this.getDateString());
                topLevelClass.addJavaDocLine(" */");
            }
        }
    
        /**
         * <p>生成xx.java文件(model)属性的注释</p>
         *
         * @param field
         * @param introspectedTable
         * @param introspectedColumn
         */
        @Override
        public void addFieldComment(Field field, IntrospectedTable introspectedTable, IntrospectedColumn introspectedColumn) {
            if (!this.suppressAllComments) {
                // 注释开始的地方
                field.addJavaDocLine("/**");
                String remarks = introspectedColumn.getRemarks();
                // 开启注释,并且数据库中comment有值
                if (this.addRemarkComments && StringUtility.stringHasValue(remarks)) {
                    // 通过换行符分割 System.getProperty("line.separator"):换行符 ,屏蔽了 Windows和Linux的区别
                    String[] remarkLines = remarks.split(System.getProperty("line.separator"));
                    int length = remarkLines.length;
                    // 如果有多行,就换行显示
                    for (int i = 0; i < length; i++) {
                        String remarkLine = remarkLines[i];
                        field.addJavaDocLine(" * " + remarkLine);
                    }
                }
                // 注释结束
                field.addJavaDocLine(" */");
            }
        }
    
        /**
         * xxxMapper接口和xxxExample类方法注解
         *
         * @param method
         * @param introspectedTable
         */
        @Override
        public void addGeneralMethodComment(Method method, IntrospectedTable introspectedTable) {
            if (!this.suppressAllComments) {
                method.addJavaDocLine("/**");
                method.addJavaDocLine(" * " + method.getName());
                List<Parameter> parameters = method.getParameters();
                parameters.forEach(parameter -> method.addJavaDocLine(" * @param " + parameter.getName()));
                // 如果有返回类型,添加@return
                String returnType = "void";
                if (!returnType.equals(method.getReturnType())) {
                    method.addJavaDocLine(" * @return ");
                }
                method.addJavaDocLine(" */");
            }
    
        }
    
        /**
         * 数据库对应实体类的Getter方法注解
         *
         * @param method
         * @param introspectedTable
         * @param introspectedColumn
         */
        @Override
        public void addGetterComment(Method method, IntrospectedTable introspectedTable, IntrospectedColumn introspectedColumn) {
    
        }
    
        /**
         * 数据库对应实体类的Setter方法注解
         *
         * @param method
         * @param introspectedTable
         * @param introspectedColumn
         */
        @Override
        public void addSetterComment(Method method, IntrospectedTable introspectedTable, IntrospectedColumn introspectedColumn) {
    
        }
    
        /**
         * 生成xxMapper.XML文件的注释
         *
         * @param xmlElement
         */
        @Override
        public void addComment(XmlElement xmlElement) {
        }
    
        @Override
        public void addGeneralMethodAnnotation(Method method, IntrospectedTable introspectedTable, Set<FullyQualifiedJavaType> imports) {
    
        }
    
        @Override
        public void addGeneralMethodAnnotation(Method method, IntrospectedTable introspectedTable, IntrospectedColumn introspectedColumn, Set<FullyQualifiedJavaType> imports) {
    
        }
    
        @Override
        public void addFieldAnnotation(Field field, IntrospectedTable introspectedTable, Set<FullyQualifiedJavaType> imports) {
    
        }
    
        @Override
        public void addFieldAnnotation(Field field, IntrospectedTable introspectedTable, IntrospectedColumn introspectedColumn, Set<FullyQualifiedJavaType> imports) {
        }
    
        @Override
        public void addClassAnnotation(InnerClass innerClass, IntrospectedTable introspectedTable, Set<FullyQualifiedJavaType> imports) {
        }
    
        @Override
        public void addJavaFileComment(CompilationUnit compilationUnit) {
        }
    
        @Override
        public void addRootComment(XmlElement rootElement) {
        }
    
        @Override
        public void addFieldComment(Field field, IntrospectedTable introspectedTable) {
    
        }
    
        @Override
        public void addEnumComment(InnerEnum innerEnum, IntrospectedTable introspectedTable) {
    
        }
    
        @Override
        public void addClassComment(InnerClass innerClass, IntrospectedTable introspectedTable) {
    
        }
    
        @Override
        public void addClassComment(InnerClass innerClass, IntrospectedTable introspectedTable, boolean markAsDoNotDelete) {
    
        }
    
    }
    

    1.7.2.在generatorConfig.xml配饰文件中添加

    <!--注释:课可通过type自动配置-->
    <commentGenerator type="cn.edu.nwafu.ssr.community.MyCommentGenerator">
        <property name="addRemarkComments" value="true"/>
    </commentGenerator>
    

    1.7.3. 通过java方式启动mbg ,maven会出现一些问题

    package cn.edu.nwafu.ssr.community;
    
    import org.mybatis.generator.api.MyBatisGenerator;
    import org.mybatis.generator.config.Configuration;
    import org.mybatis.generator.config.xml.ConfigurationParser;
    import org.mybatis.generator.internal.DefaultShellCallback;
    
    import java.io.File;
    import java.util.ArrayList;
    import java.util.List;
    
    /**
     * @author shensr
     * @version V1.0
     * @description 通过java方式启动mbg,实现自定配置注解,使用maven方式会出现问题
     * @create 2019/10/9
     **/
    
    public class Generator {
        public static void main(String[] args)  {
            List<String> warnings = new ArrayList<>();
            // 覆盖
            boolean overwrite = true;
            // 给出generatorConfig.xml文件的位置
            File configFile = new File("D:\\IdeaProjects\\blog_community\\src\\main\\resources\\generatorConfig.xml");
            ConfigurationParser cp = new ConfigurationParser(warnings);
            try {
                Configuration config = cp.parseConfiguration(configFile);
                DefaultShellCallback callback = new DefaultShellCallback(overwrite);
                MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
                myBatisGenerator.generate(null);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    
    

    1.7.8. 生成效果

    package cn.edu.nwafu.ssr.community.model;
    
    /**
     * @author shensr
     * @version V1.0 
     * @description MyBatis Generator 自动创建,对应数据表为:tb_user
     * @create 2019/10/09
     */
    public class User {
        /**
         * ID 
         */
        private Integer id;
    
        /**
         * 账户Id
         */
        private String accountId;
    
        /**
         * 用户名
         */
        private String name;
    
        /**
         * token
         */
        private String token;
    
        /**
         * 创建时间
         */
        private Long gmtCreate;
    
        /**
         * 更新时间
         */
        private Long gmtModified;
    
        public Integer getId() {
            return id;
        }
    
        public void setId(Integer id) {
            this.id = id;
        }
    
        public String getAccountId() {
            return accountId;
        }
    
        public void setAccountId(String accountId) {
            this.accountId = accountId == null ? null : accountId.trim();
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name == null ? null : name.trim();
        }
    
        public String getToken() {
            return token;
        }
    
        public void setToken(String token) {
            this.token = token == null ? null : token.trim();
        }
    
        public Long getGmtCreate() {
            return gmtCreate;
        }
    
        public void setGmtCreate(Long gmtCreate) {
            this.gmtCreate = gmtCreate;
        }
    
        public Long getGmtModified() {
            return gmtModified;
        }
    
        public void setGmtModified(Long gmtModified) {
            this.gmtModified = gmtModified;
        }
    }
    

    相关文章

      网友评论

          本文标题:Mybatis Generator 自定义注释

          本文链接:https://www.haomeiwen.com/subject/qvngpctx.html