Mybatis Generator的model生成中文註釋,支持oracle和mysql(經過實現CommentGenerator接口的方法來實現)

本身手動實現的前提,對maven項目有基本的瞭解,在本地成功搭建了maven環境,能夠參考我以前的文章:maven環境搭建html

項目裏新建表時model,mapper以及mapper.xml基本都是用Mybatis Generator(如下簡稱爲MBG)自動生成的,可是MBG自動生成的model的註釋實在有點非人類,至少中國人是徹底接受不了的,在配置中禁用掉註釋吧,卻是簡單了,但是生成的model類光禿禿的,啥都沒有,字段方法沒有註釋,使用很不方便,別人看也不知道這個字段是啥含義,到最後仍是要本身添加,一張表多點幾十個字段,特麼添加累死了,不能這麼幹,得想法子,百度了一下網上,基本有兩種方法,第一種,就是直接修改MGB的源代碼,第二種就是本身寫一個類實現CommentGenerator接口,先說本身寫一個新類實現CommentGenerator接口的方法來使自動生成的model類含有中文註釋吧.java

  • 1.首先新建一個maven項目,請選擇一個簡單的maven項目:或者在選擇的時候直接選擇create a simple project.

  • 2,右鍵項目->build path->config build path...->Libraries,修改jdk爲你工做空間的默認jdk,而後右鍵項目->new->source folder,輸入src/main/resources,建好resources目錄,若是已經建好就直接跳過.這裏最好不要忘記,不然有的時候創建默認jdk是1.5的,運行可能會有莫名其妙的問題.
  • 3 由於是要寫一個類實現CommentGenerator接口,因此先在項目中引入mybatis-generator-core的jar包 在pom.xml中添加依賴, 這裏統一使用1.3.2版本.爲了避免用每次使用都要使用者本身指定ojdbc6.jar位置,直接將其引入到項目中,這裏要使用該引入,須要先將jar包安裝到本地maven倉庫中,不然這裏這樣引入會報錯的,怎麼安裝能夠參考這篇文章:

    maven手動安裝jar包到本地倉庫,以ojdbc6爲例,

   同時爲了支持mysql,也一塊兒加入mysql的驅動包,mysql的驅動包不用手動安裝,直接引入就會自動下載的mysql

<dependency>
     <groupId>org.mybatis.generator</groupId>
     <artifactId>mybatis-generator-core</artifactId>
     <version>1.3.2</version>
</dependency>
<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>
  • 4 在源代碼中新建一個類MyCommentGenerator,實現CommentGenerator接口,類的代碼以下:
package org.mybatis.generator;

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;

/**
 * 描述:
 * @since 1.9.10
 * @version 1.9.10
 * @做者:niexiaohui
 * @建立時間:2016年11月22日
 * @修改記錄:
 */
public class MyCommentGenerator implements CommentGenerator{
    private Properties properties;
    private Properties systemPro;
    private boolean suppressDate;
    private boolean suppressAllComments;
    private String currentDateStr;

    public MyCommentGenerator() {
        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(" * @author ");
        sb.append(systemPro.getProperty("user.name"));
        sb.append(" ");
        sb.append(currentDateStr);
        innerClass.addJavaDocLine(" */");
    }
}
View Code
  • 5.再新建一個類StartUp,用於運行項目,類的代碼以下:
package org.mybatis.generator;

import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.config.Configuration;
import org.mybatis.generator.config.xml.ConfigurationParser;
import org.mybatis.generator.exception.InvalidConfigurationException;
import org.mybatis.generator.exception.XMLParserException;
import org.mybatis.generator.internal.DefaultShellCallback;

/**
 * 描述:
 * @since 1.9.10
 * @version 1.9.10
 * @做者:niexiaohui
 * @建立時間:2016年11月22日
 * @修改記錄:
 */
public class StartUp {
    public static void main(String[] args) throws URISyntaxException {
        try {
            List<String> warnings = new ArrayList<String>();
            boolean overwrite = true;
            ClassLoader classloader = Thread.currentThread().getContextClassLoader();
            InputStream is = classloader.getResourceAsStream("generatorConfig.xml");
            ConfigurationParser cp = new ConfigurationParser(warnings);
            Configuration config = cp.parseConfiguration(is);
            DefaultShellCallback callback = new DefaultShellCallback(overwrite);
            MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
            myBatisGenerator.generate(null);
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (InvalidConfigurationException e) {
            e.printStackTrace();
        } catch (XMLParserException e) {
            e.printStackTrace();
        }
    }
}
View Code
  • 6. 而後將generatorConfig.xml放入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>
    <!-- ojdbc6.jar已經直接放到項目中,無需指定了,同時mysql驅動包也同樣,這裏一樣無需指定 -->
    <!-- <classPathEntry location="ojdbc6.jar" /> -->
    <context id="context1" targetRuntime="MyBatis3">
        <!-- 指定生成的java文件的編碼,沒有直接生成到項目時中文可能會亂碼 -->
        <property name="javaFileEncoding" value="UTF-8"/>
        <!-- 這裏的type裏寫的是你的實現類的類全路徑 -->
        <commentGenerator type="org.mybatis.generator.MyCommentGenerator">
        </commentGenerator>

        <jdbcConnection driverClass="oracle.jdbc.driver.OracleDriver"
            connectionURL="jdbc:oracle:thin:@遠程ip地址或localhost: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="ABS_DEAL" domainObjectName="AbsDeal" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"> </table> </context> </generatorConfiguration>

到此爲止項目的結構以下:sql

 這個時候咱們運行StartUp的main方法,已經能夠實現了,發現桌面上生成了兩個文件夾,model和mapper文件夾,裏面有生成的文件.看一下效果:數據庫

是否是很符合中國人的審美觀呢,若是不滿意,或者有什麼要加的,能夠本身在實現類中加入代碼修改,addFieldComment,addGetterComment,addSetterComment這幾個方法就好了,裏面的代碼也很容易看懂,很容易改.apache

  • 6.到此爲止雖然已經生成成功了,可是事情還不算完,不能要求每一個人都從無到有搞這麼一個項目,因此要把它打成一個能夠運行的jar包才行.這裏要使依賴包被打包到最後的jar包中,要在pom.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>mygenerator</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

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

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

    <dependencies>
        <dependency>
            <groupId>org.mybatis.generator</groupId>
            <artifactId>mybatis-generator-core</artifactId>
            <version>1.3.2</version>
        </dependency>
        <dependency>
            <groupId>com.oracle</groupId>
            <artifactId>ojdbc6</artifactId>
            <version>6.0</version>
        </dependency>
    </dependencies>
    
    <build>
        <!-- 這裏指定最終生成的jar包的名字,爲了盜版到底,直接使用原先的名稱,嘿嘿 -->
        <finalName>mybatis-generator-core-1.3.2</finalName>
        <plugins>
            <plugin>
                <!-- 由於項目中使用了依賴包,因此要使用maven-assembly-plugin來構建,會把依賴包同時打進jar包中 -->
                <artifactId>maven-assembly-plugin</artifactId>
                <version>2.6</version>
                <configuration>
                    <!-- 這裏不指定爲false打包會生成兩個jar包,咱們要用的那個jar包命名很亂,後面加了
                    jar-with-dependencies,不喜歡,直接禁用掉 -->
                    <appendAssemblyId>false</appendAssemblyId>
                    <archive>
                        <manifest>
                            <!-- 指定main方法的類的全路徑  不然運行會報找不到main class的錯誤-->
                            <mainClass>org.mybatis.generator.StartUp</mainClass>
                        </manifest>
                    </archive>
                    <descriptorRefs>
                        <descriptorRef>jar-with-dependencies</descriptorRef>
                    </descriptorRefs>
                </configuration>
                <executions>
                    <execution>
                        <id>make-assembly</id>
                        <phase>package</phase>
                        <goals>
                            <goal>single</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
    
</project>
View Code

到這裏項目就完成了,在項目根路徑使用打包命令mvn clean package,固然能夠在eclipse中使用maven build中輸入命令來生成,我習慣使用控制檯來生成,在項目根路徑,按住shift的同時右鍵,選擇在此處打開命令窗口,而後輸入mvn clean package命令按下enter,固然這些能夠實現的前提是你本地maven環境配置好了,若是沒有設置maven_home環境變量的話運行會提示沒法識別的mvn命令的,成功構建後顯示build success,到target目錄下,看到生成了jar包:api

一樣在target目錄下:按住shift同時右鍵->在此處打開命令行,輸入java -jar mybatis-generator-core-1.3.2.jar命令運行jar包,注意-jar後打出my時按tab鍵mybatis-generator-core-1.3.2.jar就自動補全了,運行結束後,一樣的在桌面上回看到生成的model和mapper文件夾及裏面的文件.這裏是測試,因此配置中寫文件生成在了桌面上,能夠改一下配置,設置在項目中輸出,直接輸出到項目中.mybatis

固然爲了使用方便,不用每次都輸入java -jar mybatis-generator-core-1.3.2.jar命令,能夠把命令放入腳本文件中,新建一個記事本,重命名爲generator.bat,而後把java -jar mybatis-generator-core-1.3.2.jar命令拷貝進去,之後只要雙擊generator.bat就能夠直接生成了,固然你的generator.bat得和jar包在同一個目錄下.oracle

 

還有要修改generatorConfig.xml文件可使用壓縮軟件打開mybatis-generator-core-1.3.2.jar,雙擊generatorConfig.xml,修改後保存並更新回壓縮包.由於這裏StartUp文件中使用的是加載generatorConfig.xml的方法,因此會加載jar包裏的generatorConfig.xml配置文件,若是StartUp文件中加載配置文件的方式使用MBG原生態的加載方式,就可使用jar包同目錄下的generatorConfig.xml,不過那時運行命令就爲:java -jar mybatis-generator-core-1.3.2.jar -configfile generatorConfig.xml -overwrite,我以爲這樣挺好的,不用每次都拖着一個generatorConfig.xml,移動都不方便,放在jar包裏跟着跑挺方便的.app

 

抱歉,使用了才知道,generatorConfig.xml放在jar包裏彷佛生成到項目裏很差配置,只能寫絕對路徑,相對路徑好像很差弄,能夠稍微修改一下,用MBG原來的加載外部的generatorConfig.xml,只須要修改pom.xml的構建中的main class節點由startup改成org.mybatis.generator.api.ShellRunner而後從新打包,運行jar包時命令爲

java -jar mybatis-generator-core-1.3.2.jar -configfile generatorConfig.xml -overwrite,如下提供的下載更新爲使用ShellRunner運行的.若是使用ShellRunner運行,則以前的startup能夠刪除了,項目resource目錄下的generatorConfig.xml也不須要了,直接使用外部的generatorConfig.xml.

 生成的jar包下載:  MybatisGenerator

 

固然經過實現藉口來實現仍是有必定問題的,下一篇直接經過修改源代碼來實現:

下一篇:Mybatis Generator的model生成中文註釋,支持oracle和mysql(經過修改源碼的方式來實現)

相關文章
相關標籤/搜索