1. 程式人生 > >Mybatis Generator的model生成中文註釋,支援oracle和mysql(通過修改原始碼的方式來實現)

Mybatis Generator的model生成中文註釋,支援oracle和mysql(通過修改原始碼的方式來實現)

在看本篇之前,最好先看一下上一篇通過實現CommentGenerator介面的方法來實現中文註釋的例子,因為很多操作和上一篇基本是一致的,所以本篇可能不那麼詳細.

首先說一下上篇通過實現CommentGenerator介面的一些不足,畢竟只是實現了CommentGenerator介面,在裡面的方法再怎麼改,有效的也只是針對model類,並且使用的人大概也發現了,裡面的addClassComment方法都知道是在類檔案上面生成註釋,但是無論我們在這個方法實現裡寫什麼都沒有效果,其實因為MGB預設是沒有呼叫這個方法的,這個時候如果有需求希望生成的類檔案自動加了類文件說明就辦不到了,而如果在原始碼的基礎上修改,就好辦多了,想怎麼改就怎麼改,只要找對地方,什麼樣的需要都可以自己寫程式碼來實現.

  • 首先一樣,自己新建一個maven專案,怎麼做就不詳細說了,前一篇有,都弄好後,修改pom.xml檔案,首先引入MBG的原始碼,在pom.xml中加入依賴
    <dependency>
            <groupId>org.mybatis.generator</groupId>
            <artifactId>mybatis-generator-core</artifactId>
            <version>1.3.2</version>
        </dependency>

  儲存過後就會自動下載mybatis-generator-core的jar包,然後我們到自己的本地倉庫中去找存放這個jar包的位置,下載下來後pom.xml中這個依賴可以刪除了.

我們會看到不僅下載了jar包,原始碼也一起下載了,用壓縮軟體開啟source,jar,複製org資料夾及其內所有檔案到自己的eclipse建立的maven專案中,這樣就取得了MBG的原始碼,你也可以在

http://search.maven.org中搜索mybatis-generator-core然後點選source.jar來直接下載原始碼.

  • 第一步得到原始碼後之後,複製到專案中我們會發現是報錯的,因為有依賴包沒有引入,缺少log4j和ant包,在pom.xml中新增上依賴,順便添加了oracle和mysql的驅動程式包,oracle的本地安裝從上一篇中可以看到,加入後項目就沒有錯誤了
複製程式碼
      <dependency>
            <groupId>com.oracle</groupId>
            <artifactId>ojdbc6</artifactId>
            <version>6.0</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.9</version>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.7</version>
        </dependency>
        <dependency>
            <groupId>org.apache.ant</groupId>
            <artifactId>ant</artifactId>
            <version>1.9.0</version>
        </dependency>
複製程式碼

這個時候我們的專案結構應該是這個樣子的

然後就很簡單了,在原始碼裡找到 org.mybatis.generator.internal.DefaultCommentGenerator類,隨便改吧,自己diy,以下是一個樣本

 View Code
/*
 *  Copyright 2008 The Apache Software Foundation
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

package org.mybatis.generator.internal;

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

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

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.CompilationUnit;
import org.mybatis.generator.api.dom.java.Field;
import org.mybatis.generator.api.dom.java.InnerClass;
import org.mybatis.generator.api.dom.java.InnerEnum;
import org.mybatis.generator.api.dom.java.JavaElement;
import org.mybatis.generator.api.dom.java.Method;
import org.mybatis.generator.api.dom.java.Parameter;
import org.mybatis.generator.api.dom.xml.XmlElement;
import org.mybatis.generator.config.MergeConstants;
import org.mybatis.generator.config.PropertyRegistry;

/**
 * @author Jeff Butler
 * 
 */
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());
    }

    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.
     */
    public void addComment(XmlElement xmlElement) {
        return;
    }

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

    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;
    }

    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().replace("\n", " "));
        innerClass.addJavaDocLine(" */");
    }

    public void addEnumComment(InnerEnum innerEnum, IntrospectedTable introspectedTable) {
        if (suppressAllComments) {
            return;
        }
        StringBuilder sb = new StringBuilder();
        innerEnum.addJavaDocLine("/**");
        sb.append(" * ");
        sb.append(introspectedTable.getFullyQualifiedTable());
        innerEnum.addJavaDocLine(sb.toString().replace("\n", " "));
        innerEnum.addJavaDocLine(" */");
    }

    public void addFieldComment(Field field, IntrospectedTable introspectedTable,
            IntrospectedColumn introspectedColumn) {
        if (suppressAllComments) {
            return;
        }
        StringBuilder sb = new StringBuilder();
        field.addJavaDocLine("/**");
        sb.append(" * ");
        sb.append(introspectedColumn.getRemarks());
        field.addJavaDocLine(sb.toString().replace("\n", " "));
        field.addJavaDocLine(" */");
    }

    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().replace("\n", " "));
        field.addJavaDocLine(" */");
    }

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

    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().replace("\n", " "));
        sb.setLength(0);
        sb.append(" * @return ");
        sb.append(introspectedColumn.getActualColumnName());
        sb.append(" ");
        sb.append(introspectedColumn.getRemarks());
        method.addJavaDocLine(sb.toString().replace("\n", " "));
        method.addJavaDocLine(" */");
    }

    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().replace("\n", " "));
        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().replace("\n", " "));
        method.addJavaDocLine(" */");
    }

    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().replace("\n", " "));
        sb.setLength(0);
        sb.append(" * @version");
        innerClass.addJavaDocLine(sb.toString().replace("\n", " "));
        sb.setLength(0);
        sb.append(" * @author:  ");
        sb.append(systemPro.getProperty("user.name"));
        innerClass.addJavaDocLine(sb.toString().replace("\n", " "));
        sb.setLength(0);
        sb.append(" * @建立時間: ");
        sb.append(currentDateStr);
        innerClass.addJavaDocLine(sb.toString().replace("\n", " "));
        innerClass.addJavaDocLine(" */");
    }
}


為了是辛辛苦苦寫的addClassComment生效,還得找到org.mybatis.generator.codegen.mybatis3.model.BaseRecordGenerator類,在大約60行的地方,在commentGenerator.addJavaFileComment(topLevelClass);後加一句:

 commentGenerator.addClassComment(topLevelClass, introspectedTable,false);

這樣自己的方法就呼叫到了,說明一下,仔細看一下原始碼,會發現DefaultCommentGenerator類,會發現addClassComment方法有兩個,一個加了boolean markAsDoNotDelete引數,一個沒有加,你這裡呼叫的如果不加false引數,就改DefaultCommentGenerator類中兩個引數的addClassComment方法,我的樣例中你會發現方法中傳了引數也不管用,因為真正的原始碼中是有這麼一行的

然後addJavadocTag方法中是這麼呼叫的

我的樣例中addJavadocTag方法的呼叫都被刪除了,所以傳個引數也沒啥用.

  • 其他的如果想有什麼改動,就自己去研究原始碼,然後自己手動改了,到這裡就差不多結束了,剩下的工作和上次的一樣,使用mvn clean package命令打成jar包,然後在控制檯使用

java -jar mybatis-generator-core-1.3.2.jar -configfile generatorConfig.xml -overwrite命令執行,貼一下完整的pom.xml和generatorConfig.xml,部分地方和上次還是有區別的.

pom.xml:

複製程式碼
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.mybatis</groupId>
    <artifactId>mybatis-generator-coree</artifactId>
    <version>1.3.2</version>
    <packaging>jar</packaging>

    <name>MybatisGenerator</name>
    <url>http://maven.apache.org</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <dependency>
            <groupId>com.oracle</groupId>
            <artifactId>ojdbc6</artifactId>
            <version>6.0</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.9</version>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.7</version>
        </dependency>
        <dependency>
            <groupId>org.apache.ant</groupId>
            <artifactId>ant</artifactId>
            <version>1.9.0</version>
        </dependency>
    </dependencies>


    <build>
        <finalName>mybatis-generator-core-1.3.2</finalName>
        <plugins>
            <plugin>
                <artifactId>maven-assembly-plugin</artifactId>
                <version>2.6</version>
                <configuration>
                    <appendAssemblyId>false</appendAssemblyId>
                    <archive>
                        <manifest>
                            <mainClass>org.mybatis.generator.api.ShellRunner</mainClass>
                        </manifest>
                    </archive>
                    <descriptorRefs>
                        <descriptorRef>jar-with-dependencies</descriptorRef>
                    </descriptorRefs>
                </configuration>
                <executions>
                    <execution>
                        <id>make-assembly</id>
                        <phase>package</phase>
                        <goals>
                            <goal>assembly</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>
複製程式碼

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="context1" targetRuntime="MyBatis3">
        <!-- 指定生成的java檔案的編碼,沒有直接生成到專案時中文可能會亂碼 -->
        <property name="javaFileEncoding" value="UTF-8"/>
        <!-- oracle配置 -->
<!--             <jdbcConnection driverClass="oracle.jdbc.driver.OracleDriver"
            connectionURL="jdbc:oracle:thin:@***:1521:orcl" userId="***"
            password="***">
            針對oracle資料庫
            <property name="remarksReporting" value="true"></property>
        </jdbcConnection> -->
        
         <!-- mysql配置 -->
          <jdbcConnection driverClass="com.mysql.jdbc.Driver"
                  connectionURL="jdbc:mysql://localhost:3306/bookshop" userId="root"
                  password="root">
                    <!-- 針對mysql資料庫 -->
                    <property name="useInformationSchema" value="true"></property>
          </jdbcConnection>

        <javaTypeResolver>
            <property name="forceBigDecimals" value="false" />
        </javaTypeResolver>

        <!-- dto class -->
        <javaModelGenerator targetPackage="model"
            targetProject="C:\Users\Administrator\Desktop">
            <property name="enableSubPackages" value="true" />
            <property name="trimStrings" value="true" />
        </javaModelGenerator>

        <!-- mybatis xml file -->
        <sqlMapGenerator targetPackage="dao"
            targetProject="C:\Users\Administrator\Desktop">
            <property name="enableSubPackages" value="true" />
        </sqlMapGenerator>

        <!-- mapper class -->
        <javaClientGenerator type="XMLMAPPER"
            targetPackage="dao" targetProject="C:\Users\Administrator\Desktop">
            <property name="enableSubPackages" value="true" />
        </javaClientGenerator>


        <!--不生成幫助類(Exmaples) -->
        <!-- enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" 
            enableSelectByExample="false" selectByExampleQueryId="false" -->
        <!--已生成的表 <table schema="demo" tableName="USER" domainObjectName="User"></table> -->
        <table schema="" tableName="bookinfo" domainObjectName="BookInfo"
            enableCountByExample="false" enableUpdateByExample="false"
            enableDeleteByExample="false" enableSelectByExample="false"
            selectByExampleQueryId="false">
        </table>

    </context>
</generatorConfiguration>
複製程式碼

這裡使用的是預設的就不用指定commentGenerator節點的type屬性了.生成後的model效果如下:

生成好的工具下載:

原始碼下載: