generatorConfig自動生成實體類以及自定義生成註釋的方法

前端幼兒園發表於2020-10-06
  • 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>
  <!-- 指定資料庫驅動的jdbc驅動jar包的位置 -->
  <classPathEntry location="./mysql-connector-java-5.1.40.jar" />

  <context id="mysql" defaultModelType="hierarchical" targetRuntime="MyBatis3Simple" >
    <!-- 生成的 Java 檔案的編碼 -->
    <property name="javaFileEncoding" value="UTF-8"/>
    <!-- 格式化 Java 程式碼 -->
    <property name="javaFormatter" value="org.mybatis.generator.api.dom.DefaultJavaFormatter"/>
    <!-- 格式化 XML 程式碼 -->
    <property name="xmlFormatter" value="org.mybatis.generator.api.dom.DefaultXmlFormatter"/>

    <!-- 配置資料庫連線 -->
    <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/test?characterEncoding=utf-8" userId="root" password="123456">
    </jdbcConnection>

    <!-- 生成實體的位置 -->
    <javaModelGenerator targetPackage="me.mizhoux.model" targetProject="src/main/java">
      <property name="enableSubPackages" value="true"/>
    </javaModelGenerator>

    <!-- 生成 Mapper 介面的位置 -->
    <sqlMapGenerator targetPackage="me.mizhoux.mapper" targetProject="src/main/java">
      <property name="enableSubPackages" value="true"/>
    </sqlMapGenerator>

    <!-- 生成 Mapper XML 的位置 -->
    <javaClientGenerator targetPackage="me.mizhoux.mapper" type="XMLMAPPER" targetProject="src/main/java">
      <property name="enableSubPackages" value="true"/>
    </javaClientGenerator>

    <!-- 設定資料庫的表名和實體類名 -->
    <table tableName="t_user" domainObjectName="User">
      <!-- generatedKey用於生成生成主鍵的方法 -->
      <generatedKey column="id" sqlStatement="SELECT LAST_INSERT_ID()"/>
    </table>

  </context>

</generatorConfiguration>

  • addRemarkComments 這個屬性,就是用來生成資料庫註釋用的,設定成true就會生成註釋
<commentGenerator>
      <property name="suppressDate" value="true"/>
      <property name="addRemarkComments" value="true"/>
    </commentGenerator>
  • 但是使用這個方法生成出來的實體類雖然註解出來了,但是多了一堆看不懂的英文。這些內容已經寫死在 DefaultCommentGenerator 中了,沒有辦法自定義。
    在這裡插入圖片描述

  • 我們可以自己寫個類實現 CommentGenerator 介面,然後自定義自己想要的註釋,但不做任何操作 —— 因為 DefaultCommentGenerator 本文已經存在了,為了避免混淆,就叫它SimpleCommentGenerator吧

package com.chao.util;

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 java.util.Properties;

public class SimpleCommentGenerator implements CommentGenerator {
    public void addConfigurationProperties(Properties properties) {

    }

    public void addFieldComment(Field field, IntrospectedTable introspectedTable, IntrospectedColumn introspectedColumn) {

    }

    public void addFieldComment(Field field, IntrospectedTable introspectedTable) {

    }

    public void addModelClassComment(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {

    }

    public void addClassComment(InnerClass innerClass, IntrospectedTable introspectedTable) {

    }

    public void addClassComment(InnerClass innerClass, IntrospectedTable introspectedTable, boolean b) {

    }

    public void addEnumComment(InnerEnum innerEnum, IntrospectedTable introspectedTable) {

    }

    public void addGetterComment(Method method, IntrospectedTable introspectedTable, IntrospectedColumn introspectedColumn) {

    }

    public void addSetterComment(Method method, IntrospectedTable introspectedTable, IntrospectedColumn introspectedColumn) {

    }

    public void addGeneralMethodComment(Method method, IntrospectedTable introspectedTable) {

    }

    public void addJavaFileComment(CompilationUnit compilationUnit) {

    }

    public void addComment(XmlElement xmlElement) {

    }

    public void addRootComment(XmlElement xmlElement) {

    }
}

  • 然後定義我們自己的註釋類,MySQLCommentGenerator,繼承 SimpleCommentGenerator,重寫我們需要的方法:
package com.chao.util;

import org.mybatis.generator.api.IntrospectedColumn;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.dom.java.Field;
import org.mybatis.generator.api.dom.java.TopLevelClass;

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

public class MySQLCommentGenerator extends SimpleCommentGenerator {

    private Properties properties;

    public MySQLCommentGenerator() {
        properties = new Properties();
    }

    public void addConfigurationProperties(Properties properties) {
        // 獲取自定義的 properties
        this.properties.putAll(properties);
    }

    public void addModelClassComment(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
        String author = properties.getProperty("author");
        String dateFormat = properties.getProperty("dateFormat", "yyyy-MM-dd");
        SimpleDateFormat dateFormatter = new SimpleDateFormat(dateFormat);

        // 獲取表註釋
        String remarks = introspectedTable.getRemarks();

        topLevelClass.addJavaDocLine("/**");
        topLevelClass.addJavaDocLine(" * " + remarks);
        topLevelClass.addJavaDocLine(" *");
        topLevelClass.addJavaDocLine(" * @author " + author);
        topLevelClass.addJavaDocLine(" * @date " + dateFormatter.format(new Date()));
        topLevelClass.addJavaDocLine(" */");
    }

    public void addFieldComment(Field field, IntrospectedTable introspectedTable, IntrospectedColumn introspectedColumn) {
        // 獲取列註釋
        String remarks = introspectedColumn.getRemarks();
        field.addJavaDocLine("/**");
        field.addJavaDocLine(" * " + remarks);
        field.addJavaDocLine(" */");
    }
}
  • 因為我們現在要使用到我們自己自定義的 CommentGenerator ,所以我們 通過程式碼的方式來操作
package com.chao.util;

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;

public class Generator {

    public static void main( String[] args ) throws Exception {
        List<String> warnings = new ArrayList<String>();
        File configFile = new File("src/main/resources/generatorConfig.xml");
        ConfigurationParser cp = new ConfigurationParser(warnings);
        Configuration config = cp.parseConfiguration(configFile);
        DefaultShellCallback callback = new DefaultShellCallback(true);
        MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
        myBatisGenerator.generate(null);
    }

}
  • 然後配置 generatorConfig.xml設定我們自己的註釋生成器(這裡需要注意的是如果沒有配置useInformationSchema的話,生成出來的實體類就沒有類註釋):
<!-- 設定 useInformationSchema 屬性為 true -->
       <property name="useInformationSchema" value="true" />
<?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>
    <!-- 引入配置檔案 -->
    <properties resource="database.properties"/>
    <!-- 資料庫驅動-->  
    <classPathEntry  location="C:\Users\Mr He\.m2\repository\mysql\mysql-connector-java\5.1.47\mysql-connector-java-5.1.47.jar"/>
    <context id="DB2Tables"  targetRuntime="MyBatis3">
        <!-- 自定義註釋生成器 -->
        <commentGenerator type="com.chao.util.MySQLCommentGenerator">
            <property name="author" value="Michael Chow"/>
            <property name="dateFormat" value="yyyy/MM/dd"/>
        </commentGenerator>
        <!--資料庫連結URL,使用者名稱、密碼 -->  
        <jdbcConnection driverClass="${jdbc.driver}" connectionURL="${jdbc.url}" userId="${jdbc.username}" password="${jdbc.password}">
            <!-- 設定 useInformationSchema 屬性為 true -->
            <property name="useInformationSchema" value="true" />
        </jdbcConnection>
        <javaTypeResolver>  
            <property name="forceBigDecimals" value="false"/>  
        </javaTypeResolver>  
        <!-- 生成模型的包名和位置-->
        <javaModelGenerator targetPackage="com.chao.pojo" targetProject="src/main/java">
            <property name="enableSubPackages" value="true"/>  
            <property name="trimStrings" value="true"/>  
        </javaModelGenerator>  
        <!-- 生成對映檔案的包名和位置-->  
        <sqlMapGenerator  targetPackage="com.chao.dao" targetProject="src/main/java">
            <property name="enableSubPackages" value="true"/>  
        </sqlMapGenerator>  
        <!-- 生成DAO的包名和位置-->  
        <javaClientGenerator type="XMLMAPPER" targetPackage="com.chao.dao" targetProject="src/main/java">
            <property name="enableSubPackages" value="true"/>  
        </javaClientGenerator>  
       
       <!-- 相關表的配置 多表就配置多個  tableName表名  domainObjectName類名 -->
        <table tableName="books" domainObjectName="Books" enableCountByExample="false"
               enableDeleteByExample="false" enableSelectByExample="false"
               enableUpdateByExample="false"/>
        
    </context>  
</generatorConfiguration>  

  • 現在,我們執行主類 Generator,成功生成了資料庫中的註釋:
package com.chao.pojo;

/**
 * 書本表; InnoDB free: 4096 kB
 *
 * @author Michael Chow
 * @date 2020/10/06
 */
public class Books {
    /**
     * 書id
     */
    private Integer bookid;

    /**
     * 書名
     */
    private String bookname;

    /**
     * 數量
     */
    private Integer bookcounts;

    /**
     * 描述
     */
    private String detail;

    public Integer getBookid() {
        return bookid;
    }

    public void setBookid(Integer bookid) {
        this.bookid = bookid;
    }

    public String getBookname() {
        return bookname;
    }

    public void setBookname(String bookname) {
        this.bookname = bookname == null ? null : bookname.trim();
    }

    public Integer getBookcounts() {
        return bookcounts;
    }

    public void setBookcounts(Integer bookcounts) {
        this.bookcounts = bookcounts;
    }

    public String getDetail() {
        return detail;
    }

    public void setDetail(String detail) {
        this.detail = detail == null ? null : detail.trim();
    }
}

成功的生成了實體類和欄位註釋~

相關文章