MyBatis Generator 自定義生成註釋

註釋生成器

爲了生成db裏面的註釋,必須自定義註釋生成器java

EmptyCommentGenerator:mysql

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

public class EmptyCommentGenerator implements CommentGenerator {

    @Override
    public void addConfigurationProperties(Properties properties) {

    }

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

    }

    @Override
    public void addFieldComment(Field field, IntrospectedTable introspectedTable) {

    }

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

    }

    @Override
    public void addClassComment(InnerClass innerClass, IntrospectedTable introspectedTable) {

    }

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

    }

    @Override
    public void addEnumComment(InnerEnum innerEnum, IntrospectedTable introspectedTable) {

    }

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

    }

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

    }

    @Override
    public void addGeneralMethodComment(Method method, IntrospectedTable introspectedTable) {

    }

    @Override
    public void addJavaFileComment(CompilationUnit compilationUnit) {

    }

    @Override
    public void addComment(XmlElement xmlElement) {

    }

    @Override
    public void addRootComment(XmlElement xmlElement) {

    }

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

    }

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

    }

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

    }

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

    }

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

    }
}

MySQLCommentGenerator:sql

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

/**
 * Created by qhong on 2019/3/22 14:10
 **/
public class MySQLCommentGenerator extends EmptyCommentGenerator {

   private Properties properties;

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

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

   @Override
   public void addModelClassComment(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
      // 獲取表註釋
      String remarks = introspectedTable.getRemarks();

      topLevelClass.addJavaDocLine("/**");
      topLevelClass.addJavaDocLine(" * " + remarks);
      topLevelClass.addJavaDocLine(" */");
   }

   @Override
   public void addFieldComment(Field field, IntrospectedTable introspectedTable, IntrospectedColumn introspectedColumn) {
      // 獲取列註釋
      String remarks = introspectedColumn.getRemarks();
      field.addJavaDocLine("/**");
      field.addJavaDocLine(" * " + remarks);
      field.addJavaDocLine(" */");
   }
}

代碼生成配置

mybatis-generator.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">
<!-- 第一種mybatis逆向生成xml配置 -->
<generatorConfiguration>

  <context id="sqlserverTables" defaultModelType="flat"  targetRuntime="MyBatis3">
    <!-- 生成的 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"/>

    <plugin type="org.mybatis.generator.plugins.ToStringPlugin"/>
    <!-- 生成的pojo,將implements Serializable-->
    <plugin type="org.mybatis.generator.plugins.SerializablePlugin"></plugin>

    <!-- 自定義註釋生成器 -->
    <commentGenerator type="com.jsy.order.config.mybatis.MySQLCommentGenerator">
    </commentGenerator>

    <!-- 數據庫連接URL、用戶名、密碼 -->
    <jdbcConnection driverClass="com.mysql.jdbc.Driver"
      connectionURL="jdbc:mysql://18.16.200.42:3306/personnel-dev"
      userId="root"
      password="shitou$root">
      <!-- 設置 useInformationSchema 屬性爲 true -->
      <property name="useInformationSchema" value="true" />
    </jdbcConnection>

    <!--
    默認false,把JDBC DECIMAL 和 NUMERIC 類型解析爲 Integer
        true,把JDBC DECIMAL 和 NUMERIC 類型解析爲java.math.BigDecimal
    -->
    <javaTypeResolver>
      <property name="forceBigDecimals" value="false"/>
    </javaTypeResolver>

    <!--
    生成model模型,對應的包路徑,以及文件存放路徑(targetProject),targetProject能夠指定具體的路徑,如./src/main/java,
    也可使用「MAVEN」來自動生成,這樣生成的代碼會在target/generatord-source目錄下
    -->
    <!--<javaModelGenerator targetPackage="com.joey.mybaties.test.pojo" targetProject="MAVEN">-->
    <javaModelGenerator targetPackage="com.jsy.order.mybatis.entity" targetProject="./src/main/java">
      <property name="enableSubPackages" value="true"/>
      <!-- 從數據庫返回的值被清理先後的空格  -->
      <property name="trimStrings" value="true"/>
    </javaModelGenerator>

    <!--對應的mapper.xml文件  -->
    <sqlMapGenerator targetPackage="mappers" targetProject="./src/main/resources">
      <property name="enableSubPackages" value="true"/>
    </sqlMapGenerator>

    <!-- 對應的Mapper接口類文件 -->
    <javaClientGenerator type="XMLMAPPER" targetPackage="com.jsy.order.mybatis.dao" targetProject="./src/main/java">
      <property name="enableSubPackages" value="true"/>
    </javaClientGenerator>


    <!--生成對應表及類名-->
    <!--<table tableName="stocktradeinfo" domainObjectName="StockTradeInfo" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table>-->
    <table tableName="tb_order" domainObjectName="Order" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table>

    <table tableName="tb_resident_customer_info" domainObjectName="ResidentCustomerInfo" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table>


  </context>
</generatorConfiguration>

注意其中的commentGenerator節點,引用的是自定義的類segmentfault

上面的網上都有,可是網上通常都是本身寫main方法調用api

我這邊不想寫main方法,仍是用maven插件命令進行調用mybatis

pom.xml插件配置:

<build>
    <pluginManagement>
        <plugins>
            <plugin>
                <groupId>org.mybatis.generator</groupId>
                <artifactId>mybatis-generator-maven-plugin</artifactId>
                <version>1.3.7</version>
                <dependencies>
                    <dependency>
                        <groupId> mysql</groupId>
                        <artifactId> mysql-connector-java</artifactId>
                        <version> 5.1.39</version>
                    </dependency>
                    <dependency>
                        <groupId>org.mybatis.generator</groupId>
                        <artifactId>mybatis-generator-core</artifactId>
                        <version>1.3.7</version>
                    </dependency>
                    <dependency>
                        <groupId>com.jsy</groupId>
                        <artifactId>order-persistence</artifactId>
                        <version>1.0.0-SNAPSHOT</version>
                    </dependency>
                </dependencies>

                <executions>
                    <execution>
                        <id>Generate MyBatis Artifacts</id>
                        <!--<phase>package</phase>-->
                        <!--<goals>-->
                            <!--<goal>generate</goal>-->
                        <!--</goals>-->
                    </execution>
                </executions>
                <configuration>
                    <!--容許移動生成的文件 -->
                    <verbose>true</verbose>
                    <!-- 是否覆蓋 -->
                    <overwrite>true</overwrite>
                    <!-- 自動生成的配置 -->
                    <configurationFile>
                        src/main/resources/mybatis-generator.xml</configurationFile>
                </configuration>
            </plugin>
        </plugins>
    </pluginManagement>
</build>

goal:

其中goals註釋,是由於mybatis-generator.xml中,若是沒有table標籤,那麼package就會報錯app

[ERROR] Failed to execute goal org.mybatis.generator:mybatis-generator-maven-plugin:1.3.7:generate (Generate MyBatis Artifacts) on project order-persistence: XML Parser Error on line 70: 元素類型爲 "context" 的內
容不完整, 它必須匹配 "(property*,plugin*,commentGenerator?,(connectionFactory|jdbcConnection),javaTypeReso
lver?,javaModelGenerator,sqlMapGenerator?,javaClientGenerator?,table+)"。 -> [Help 1]

插件配置的引用

注意插件配置中的引用依賴dom

<dependency>
                    <groupId>com.jsy</groupId>
                    <artifactId>order-persistence</artifactId>
                    <version>1.0.0-SNAPSHOT</version>
                </dependency>

這是我項目中的一個模塊,就是上面自定義註釋生成器所在項目的模塊,並且這個模塊還要引用maven

<!-- MyBatis Generator -->
    <dependency>
      <groupId>org.mybatis.generator</groupId>
      <artifactId>mybatis-generator-core</artifactId>
      <version>1.3.7</version>
    </dependency>

mybatis-generator 的plugin有本身的classpath,咱們在項目中直接繼承的類和plugin不屬於同一個classpath

這實際上是不一樣的兩個維度。

命令生成代碼

全都配置好之後,還須要將註釋生成器所在模塊使用maven命令install到本地,

這樣就可使用下面命令生成代碼

mvn mybatis-generator:generate

若是本地並無註釋生成器所在模塊,那麼就會報異常:

[ERROR] Failed to execute goal org.mybatis.generator:mybatis-generator-maven-plugin:1.3.7:generate (default-cli) on project order-persistence: Execution default-cli of goal org.mybatis.generator:mybatis-generator-maven-plugin:1.3.7:generate failed: Cannot instantiate object of type com.jsy.order.config.mybatis.MySQLCommentGenerator -> [Help 1]

參考

MyBatis Generator 自定義生成註釋

mybatis-generator自定義註釋生成

mybatis插件--(1)--mybatis generator自定義插件或者擴展報Cannot instantiate object of type XXX

相關文章
相關標籤/搜索