Mybatis Generator的model生成中文注释,支持oracle和mysql(通过实现CommentGenerator接口的方法来实现) maven手动安装jar包到本地仓库,以ojdbc6为例,   Mybatis Generator的model生成中文注释,支持oracle和mysql(通过修改源码的方式来实现)      

转自:https://www.cnblogs.com/NieXiaoHui/p/6094144.html

自己手动实现的前提,对maven项目有基本的了解,在本地成功搭建了maven环境,可以参考我之前的文章:maven环境搭建

项目里新建表时model,mapper以及mapper.xml基本都是用Mybatis Generator(以下简称为MBG)自动生成的,但是MBG自动生成的model的注释实在有点非人类,至少中国人是完全接受不了的,在配置中禁用掉注释吧,倒是简单了,可是生成的model类光秃秃的,啥都没有,字段方法没有注释,使用很不方便,别人看也不知道这个字段是啥含义,到最后还是要自己添加,一张表多点几十个字段,特么添加累死了,不能这么干,得想法子,百度了一下网上,基本有两种方法,第一种,就是直接修改MGB的源代码,第二种就是自己写一个类实现CommentGenerator接口,先说自己写一个新类实现CommentGenerator接口的方法来使自动生成的model类含有中文注释吧.

  • 1.首先新建一个maven项目,请选择一个简单的maven项目:或者在选择的时候直接选择create a simple project.

Mybatis Generator的model生成中文注释,支持oracle和mysql(通过实现CommentGenerator接口的方法来实现)
maven手动安装jar包到本地仓库,以ojdbc6为例,
 
Mybatis Generator的model生成中文注释,支持oracle和mysql(通过修改源码的方式来实现)
 
 
 

  • 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仓库中,否则这里这样引入会报错的,怎么安装可以参考这篇文章:

   同时为了支持mysql,也一起加入mysql的驱动包,mysql的驱动包不用手动安装,直接引入就会自动下载的

Mybatis Generator的model生成中文注释,支持oracle和mysql(通过实现CommentGenerator接口的方法来实现)
maven手动安装jar包到本地仓库,以ojdbc6为例,
 
Mybatis Generator的model生成中文注释,支持oracle和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>
Mybatis Generator的model生成中文注释,支持oracle和mysql(通过实现CommentGenerator接口的方法来实现)
maven手动安装jar包到本地仓库,以ojdbc6为例,
 
Mybatis Generator的model生成中文注释,支持oracle和mysql(通过修改源码的方式来实现)
 
 
 
  • 4 在源代码中新建一个类MyCommentGenerator,实现CommentGenerator接口,类的代码如下:
Mybatis Generator的model生成中文注释,支持oracle和mysql(通过实现CommentGenerator接口的方法来实现)
maven手动安装jar包到本地仓库,以ojdbc6为例,
 
Mybatis Generator的model生成中文注释,支持oracle和mysql(通过修改源码的方式来实现)
 
 
 
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("
", " "));
        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("
", " "));
        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("
", " "));
        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("
", " "));
        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("
", " "));
        sb.setLength(0);
        sb.append(" * @return ");
        sb.append(introspectedColumn.getActualColumnName());
        sb.append(" ");
        sb.append(introspectedColumn.getRemarks());
        method.addJavaDocLine(sb.toString().replace("
", " "));
        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("
", " "));
        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("
", " "));
        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("
", " "));
        sb.setLength(0);
        sb.append(" * @author ");
        sb.append(systemPro.getProperty("user.name"));
        sb.append(" ");
        sb.append(currentDateStr);
        innerClass.addJavaDocLine(" */");
    }
}
Mybatis Generator的model生成中文注释,支持oracle和mysql(通过实现CommentGenerator接口的方法来实现)
maven手动安装jar包到本地仓库,以ojdbc6为例,
 
Mybatis Generator的model生成中文注释,支持oracle和mysql(通过修改源码的方式来实现)
 
 
 
  • 5.再新建一个类StartUp,用于运行项目,类的代码如下:
Mybatis Generator的model生成中文注释,支持oracle和mysql(通过实现CommentGenerator接口的方法来实现)
maven手动安装jar包到本地仓库,以ojdbc6为例,
 
Mybatis Generator的model生成中文注释,支持oracle和mysql(通过修改源码的方式来实现)
 
 
 
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();
        }
    }
}
Mybatis Generator的model生成中文注释,支持oracle和mysql(通过实现CommentGenerator接口的方法来实现)
maven手动安装jar包到本地仓库,以ojdbc6为例,
 
Mybatis Generator的model生成中文注释,支持oracle和mysql(通过修改源码的方式来实现)
 
 
 
  • 6. 然后将generatorConfig.xml放入resources目录下,generatorConfig.xml内容如下
Mybatis Generator的model生成中文注释,支持oracle和mysql(通过实现CommentGenerator接口的方法来实现)
maven手动安装jar包到本地仓库,以ojdbc6为例,
 
Mybatis Generator的model生成中文注释,支持oracle和mysql(通过修改源码的方式来实现)
 
 
 
<?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 >
        <!-- 指定生成的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:UsersAdministratorDesktop"> <property name="enableSubPackages" value="true" /> <property name="trimStrings" value="true" /> </javaModelGenerator> <!-- mybatis xml file --> <sqlMapGenerator targetPackage="dao" targetProject="C:UsersAdministratorDesktop"> <property name="enableSubPackages" value="true" /> </sqlMapGenerator> <!-- mapper class --> <javaClientGenerator type="XMLMAPPER" targetPackage="dao" targetProject="C:UsersAdministratorDesktop"> <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>
Mybatis Generator的model生成中文注释,支持oracle和mysql(通过实现CommentGenerator接口的方法来实现)
maven手动安装jar包到本地仓库,以ojdbc6为例,
 
Mybatis Generator的model生成中文注释,支持oracle和mysql(通过修改源码的方式来实现)
 
 
 

到此为止项目的结构如下:

Mybatis Generator的model生成中文注释,支持oracle和mysql(通过实现CommentGenerator接口的方法来实现)
maven手动安装jar包到本地仓库,以ojdbc6为例,
 
Mybatis Generator的model生成中文注释,支持oracle和mysql(通过修改源码的方式来实现)
 
 
 

 这个时候我们运行StartUp的main方法,已经可以实现了,发现桌面上生成了两个文件夹,model和mapper文件夹,里面有生成的文件.看一下效果:

Mybatis Generator的model生成中文注释,支持oracle和mysql(通过实现CommentGenerator接口的方法来实现)
maven手动安装jar包到本地仓库,以ojdbc6为例,
 
Mybatis Generator的model生成中文注释,支持oracle和mysql(通过修改源码的方式来实现)
 
 
 

是不是很符合中国人的审美观呢,如果不满意,或者有什么要加的,可以自己在实现类中加入代码修改,addFieldComment,addGetterComment,addSetterComment这几个方法就行了,里面的代码也很容易看懂,很容易改.

  • 6.到此为止虽然已经生成成功了,但是事情还不算完,不能要求每个人都从无到有搞这么一个项目,所以要把它打成一个可以运行的jar包才行.这里要使依赖包被打包到最后的jar包中,要在pom.xml中进行相应的配置,这里给出全部的pom.xml的代码:
Mybatis Generator的model生成中文注释,支持oracle和mysql(通过实现CommentGenerator接口的方法来实现)
maven手动安装jar包到本地仓库,以ojdbc6为例,
 
Mybatis Generator的model生成中文注释,支持oracle和mysql(通过修改源码的方式来实现)
 
 
 
<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>
Mybatis Generator的model生成中文注释,支持oracle和mysql(通过实现CommentGenerator接口的方法来实现)
maven手动安装jar包到本地仓库,以ojdbc6为例,
 
Mybatis Generator的model生成中文注释,支持oracle和mysql(通过修改源码的方式来实现)
 
 
 

到这里项目就完成了,在项目根路径使用打包命令mvn clean package,当然可以在eclipse中使用maven build中输入命令来生成,我习惯使用控制台来生成,在项目根路径,按住shift的同时右键,选择在此处打开命令窗口,然后输入mvn clean package命令按下enter,当然这些可以实现的前提是你本地maven环境配置好了,如果没有设置maven_home环境变量的话运行会提示无法识别的mvn命令的,成功构建后显示build success,到target目录下,看到生成了jar包:

Mybatis Generator的model生成中文注释,支持oracle和mysql(通过实现CommentGenerator接口的方法来实现)
maven手动安装jar包到本地仓库,以ojdbc6为例,
 
Mybatis Generator的model生成中文注释,支持oracle和mysql(通过修改源码的方式来实现)
 
 
 

同样在target目录下:按住shift同时右键->在此处打开命令行,输入java -jar mybatis-generator-core-1.3.2.jar命令运行jar包,注意-jar后打出my时按tab键mybatis-generator-core-1.3.2.jar就自动补全了,运行结束后,同样的在桌面上回看到生成的model和mapper文件夹及里面的文件.这里是测试,所以配置中写文件生成在了桌面上,可以改一下配置,设置在项目中输出,直接输出到项目中.

当然为了使用方便,不用每次都输入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包在同一个目录下.

还有要修改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包里跟着跑挺方便的.

抱歉,使用了才知道,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(通过修改源码的方式来实现)

、、、、、、、、、、、、、、、、、、、、、、、

 

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中这个依赖可以删除了.

Mybatis Generator的model生成中文注释,支持oracle和mysql(通过实现CommentGenerator接口的方法来实现)
maven手动安装jar包到本地仓库,以ojdbc6为例,
 
Mybatis Generator的model生成中文注释,支持oracle和mysql(通过修改源码的方式来实现)
 
 
 

我们会看到不仅下载了jar包,源代码也一起下载了,用压缩软件打开source,jar,复制org文件夹及其内所有文件到自己的eclipse建立的maven项目中,这样就取得了MBG的源代码,你也可以在

http://search.maven.org中搜索mybatis-generator-core然后点击source.jar来直接下载源码.

  • 第一步得到源代码后之后,复制到项目中我们会发现是报错的,因为有依赖包没有引入,缺少log4j和ant包,在pom.xml中添加上依赖,顺便添加了oracle和mysql的驱动程序包,oracle的本地安装从上一篇中可以看到,加入后项目就没有错误了
Mybatis Generator的model生成中文注释,支持oracle和mysql(通过实现CommentGenerator接口的方法来实现)
maven手动安装jar包到本地仓库,以ojdbc6为例,
 
Mybatis Generator的model生成中文注释,支持oracle和mysql(通过修改源码的方式来实现)
 
 
 
      <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>
Mybatis Generator的model生成中文注释,支持oracle和mysql(通过实现CommentGenerator接口的方法来实现)
maven手动安装jar包到本地仓库,以ojdbc6为例,
 
Mybatis Generator的model生成中文注释,支持oracle和mysql(通过修改源码的方式来实现)
 
 
 

这个时候我们的项目结构应该是这个样子的

Mybatis Generator的model生成中文注释,支持oracle和mysql(通过实现CommentGenerator接口的方法来实现)
maven手动安装jar包到本地仓库,以ojdbc6为例,
 
Mybatis Generator的model生成中文注释,支持oracle和mysql(通过修改源码的方式来实现)
 
 
 

然后就很简单了,在源代码里找到 org.mybatis.generator.internal.DefaultCommentGenerator类,随便改吧,自己diy,以下是一个样本

Mybatis Generator的model生成中文注释,支持oracle和mysql(通过实现CommentGenerator接口的方法来实现)
maven手动安装jar包到本地仓库,以ojdbc6为例,
 
Mybatis Generator的model生成中文注释,支持oracle和mysql(通过修改源码的方式来实现)
 
 
 
/*
 *  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("
", " "));
        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("
", " "));
        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("
", " "));
        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("
", " "));
        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("
", " "));
        sb.setLength(0);
        sb.append(" * @return ");
        sb.append(introspectedColumn.getActualColumnName());
        sb.append(" ");
        sb.append(introspectedColumn.getRemarks());
        method.addJavaDocLine(sb.toString().replace("
", " "));
        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("
", " "));
        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("
", " "));
        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("
", " "));
        sb.setLength(0);
        sb.append(" * @version");
        innerClass.addJavaDocLine(sb.toString().replace("
", " "));
        sb.setLength(0);
        sb.append(" * @author:  ");
        sb.append(systemPro.getProperty("user.name"));
        innerClass.addJavaDocLine(sb.toString().replace("
", " "));
        sb.setLength(0);
        sb.append(" * @创建时间: ");
        sb.append(currentDateStr);
        innerClass.addJavaDocLine(sb.toString().replace("
", " "));
        innerClass.addJavaDocLine(" */");
    }
}
Mybatis Generator的model生成中文注释,支持oracle和mysql(通过实现CommentGenerator接口的方法来实现)
maven手动安装jar包到本地仓库,以ojdbc6为例,
 
Mybatis Generator的model生成中文注释,支持oracle和mysql(通过修改源码的方式来实现)
 
 
 

为了是辛辛苦苦写的addClassComment生效,还得找到org.mybatis.generator.codegen.mybatis3.model.BaseRecordGenerator类,在大约60行的地方,在commentGenerator.addJavaFileComment(topLevelClass);后加一句:

 commentGenerator.addClassComment(topLevelClass, introspectedTable,false);

这样自己的方法就调用到了,说明一下,仔细看一下源代码,会发现DefaultCommentGenerator类,会发现addClassComment方法有两个,一个加了boolean markAsDoNotDelete参数,一个没有加,你这里调用的如果不加false参数,就改DefaultCommentGenerator类中两个参数的addClassComment方法,我的样例中你会发现方法中传了参数也不管用,因为真正的源代码中是有这么一行的

Mybatis Generator的model生成中文注释,支持oracle和mysql(通过实现CommentGenerator接口的方法来实现)
maven手动安装jar包到本地仓库,以ojdbc6为例,
 
Mybatis Generator的model生成中文注释,支持oracle和mysql(通过修改源码的方式来实现)
 
 
 

然后addJavadocTag方法中是这么调用的

Mybatis Generator的model生成中文注释,支持oracle和mysql(通过实现CommentGenerator接口的方法来实现)
maven手动安装jar包到本地仓库,以ojdbc6为例,
 
Mybatis Generator的model生成中文注释,支持oracle和mysql(通过修改源码的方式来实现)
 
 
 

我的样例中addJavadocTag方法的调用都被删除了,所以传个参数也没啥用.

  • 其他的如果想有什么改动,就自己去研究源代码,然后自己手动改了,到这里就差不多结束了,剩下的工作和上次的一样,使用mvn clean package命令打成jar包,然后在控制台使用

java -jar mybatis-generator-core-1.3.2.jar -configfile generatorConfig.xml -overwrite命令运行,贴一下完整的pom.xml和generatorConfig.xml,部分地方和上次还是有区别的.

pom.xml:

Mybatis Generator的model生成中文注释,支持oracle和mysql(通过实现CommentGenerator接口的方法来实现)
maven手动安装jar包到本地仓库,以ojdbc6为例,
 
Mybatis Generator的model生成中文注释,支持oracle和mysql(通过修改源码的方式来实现)
 
 
 
<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>
Mybatis Generator的model生成中文注释,支持oracle和mysql(通过实现CommentGenerator接口的方法来实现)
maven手动安装jar包到本地仓库,以ojdbc6为例,
 
Mybatis Generator的model生成中文注释,支持oracle和mysql(通过修改源码的方式来实现)
 
 
 

generatorConfig.xml:

Mybatis Generator的model生成中文注释,支持oracle和mysql(通过实现CommentGenerator接口的方法来实现)
maven手动安装jar包到本地仓库,以ojdbc6为例,
 
Mybatis Generator的model生成中文注释,支持oracle和mysql(通过修改源码的方式来实现)
 
 
 
<?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 >
        <!-- 指定生成的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:UsersAdministratorDesktop">
            <property name="enableSubPackages" value="true" />
            <property name="trimStrings" value="true" />
        </javaModelGenerator>

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

        <!-- mapper class -->
        <javaClientGenerator type="XMLMAPPER"
            targetPackage="dao" targetProject="C:UsersAdministratorDesktop">
            <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>
Mybatis Generator的model生成中文注释,支持oracle和mysql(通过实现CommentGenerator接口的方法来实现)
maven手动安装jar包到本地仓库,以ojdbc6为例,
 
Mybatis Generator的model生成中文注释,支持oracle和mysql(通过修改源码的方式来实现)
 
 
 

这里使用的是默认的就不用指定commentGenerator节点的type属性了.生成后的model效果如下:

Mybatis Generator的model生成中文注释,支持oracle和mysql(通过实现CommentGenerator接口的方法来实现)
maven手动安装jar包到本地仓库,以ojdbc6为例,
 
Mybatis Generator的model生成中文注释,支持oracle和mysql(通过修改源码的方式来实现)
 
 
 

生成好的工具下载:

MyGenerator.rar

源码下载:

MyGenerator-source.rar

 

 

在看本篇之前,最好先看一下上一篇通过实现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中这个依赖可以删除了.

Mybatis Generator的model生成中文注释,支持oracle和mysql(通过实现CommentGenerator接口的方法来实现)
maven手动安装jar包到本地仓库,以ojdbc6为例,
 
Mybatis Generator的model生成中文注释,支持oracle和mysql(通过修改源码的方式来实现)
 
 
 

我们会看到不仅下载了jar包,源代码也一起下载了,用压缩软件打开source,jar,复制org文件夹及其内所有文件到自己的eclipse建立的maven项目中,这样就取得了MBG的源代码,你也可以在

http://search.maven.org中搜索mybatis-generator-core然后点击source.jar来直接下载源码.

  • 第一步得到源代码后之后,复制到项目中我们会发现是报错的,因为有依赖包没有引入,缺少log4j和ant包,在pom.xml中添加上依赖,顺便添加了oracle和mysql的驱动程序包,oracle的本地安装从上一篇中可以看到,加入后项目就没有错误了
Mybatis Generator的model生成中文注释,支持oracle和mysql(通过实现CommentGenerator接口的方法来实现)
maven手动安装jar包到本地仓库,以ojdbc6为例,
 
Mybatis Generator的model生成中文注释,支持oracle和mysql(通过修改源码的方式来实现)
 
 
 
      <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>
Mybatis Generator的model生成中文注释,支持oracle和mysql(通过实现CommentGenerator接口的方法来实现)
maven手动安装jar包到本地仓库,以ojdbc6为例,
 
Mybatis Generator的model生成中文注释,支持oracle和mysql(通过修改源码的方式来实现)
 
 
 

这个时候我们的项目结构应该是这个样子的

Mybatis Generator的model生成中文注释,支持oracle和mysql(通过实现CommentGenerator接口的方法来实现)
maven手动安装jar包到本地仓库,以ojdbc6为例,
 
Mybatis Generator的model生成中文注释,支持oracle和mysql(通过修改源码的方式来实现)
 
 
 

然后就很简单了,在源代码里找到 org.mybatis.generator.internal.DefaultCommentGenerator类,随便改吧,自己diy,以下是一个样本

Mybatis Generator的model生成中文注释,支持oracle和mysql(通过实现CommentGenerator接口的方法来实现)
maven手动安装jar包到本地仓库,以ojdbc6为例,
 
Mybatis Generator的model生成中文注释,支持oracle和mysql(通过修改源码的方式来实现)
 
 
 
/*
 *  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("
", " "));
        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("
", " "));
        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("
", " "));
        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("
", " "));
        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("
", " "));
        sb.setLength(0);
        sb.append(" * @return ");
        sb.append(introspectedColumn.getActualColumnName());
        sb.append(" ");
        sb.append(introspectedColumn.getRemarks());
        method.addJavaDocLine(sb.toString().replace("
", " "));
        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("
", " "));
        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("
", " "));
        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("
", " "));
        sb.setLength(0);
        sb.append(" * @version");
        innerClass.addJavaDocLine(sb.toString().replace("
", " "));
        sb.setLength(0);
        sb.append(" * @author:  ");
        sb.append(systemPro.getProperty("user.name"));
        innerClass.addJavaDocLine(sb.toString().replace("
", " "));
        sb.setLength(0);
        sb.append(" * @创建时间: ");
        sb.append(currentDateStr);
        innerClass.addJavaDocLine(sb.toString().replace("
", " "));
        innerClass.addJavaDocLine(" */");
    }
}
Mybatis Generator的model生成中文注释,支持oracle和mysql(通过实现CommentGenerator接口的方法来实现)
maven手动安装jar包到本地仓库,以ojdbc6为例,
 
Mybatis Generator的model生成中文注释,支持oracle和mysql(通过修改源码的方式来实现)
 
 
 

为了是辛辛苦苦写的addClassComment生效,还得找到org.mybatis.generator.codegen.mybatis3.model.BaseRecordGenerator类,在大约60行的地方,在commentGenerator.addJavaFileComment(topLevelClass);后加一句:

 commentGenerator.addClassComment(topLevelClass, introspectedTable,false);

这样自己的方法就调用到了,说明一下,仔细看一下源代码,会发现DefaultCommentGenerator类,会发现addClassComment方法有两个,一个加了boolean markAsDoNotDelete参数,一个没有加,你这里调用的如果不加false参数,就改DefaultCommentGenerator类中两个参数的addClassComment方法,我的样例中你会发现方法中传了参数也不管用,因为真正的源代码中是有这么一行的

Mybatis Generator的model生成中文注释,支持oracle和mysql(通过实现CommentGenerator接口的方法来实现)
maven手动安装jar包到本地仓库,以ojdbc6为例,
 
Mybatis Generator的model生成中文注释,支持oracle和mysql(通过修改源码的方式来实现)
 
 
 

然后addJavadocTag方法中是这么调用的

Mybatis Generator的model生成中文注释,支持oracle和mysql(通过实现CommentGenerator接口的方法来实现)
maven手动安装jar包到本地仓库,以ojdbc6为例,
 
Mybatis Generator的model生成中文注释,支持oracle和mysql(通过修改源码的方式来实现)
 
 
 

我的样例中addJavadocTag方法的调用都被删除了,所以传个参数也没啥用.

  • 其他的如果想有什么改动,就自己去研究源代码,然后自己手动改了,到这里就差不多结束了,剩下的工作和上次的一样,使用mvn clean package命令打成jar包,然后在控制台使用

java -jar mybatis-generator-core-1.3.2.jar -configfile generatorConfig.xml -overwrite命令运行,贴一下完整的pom.xml和generatorConfig.xml,部分地方和上次还是有区别的.

pom.xml:

Mybatis Generator的model生成中文注释,支持oracle和mysql(通过实现CommentGenerator接口的方法来实现)
maven手动安装jar包到本地仓库,以ojdbc6为例,
 
Mybatis Generator的model生成中文注释,支持oracle和mysql(通过修改源码的方式来实现)
 
 
 
<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>
Mybatis Generator的model生成中文注释,支持oracle和mysql(通过实现CommentGenerator接口的方法来实现)
maven手动安装jar包到本地仓库,以ojdbc6为例,
 
Mybatis Generator的model生成中文注释,支持oracle和mysql(通过修改源码的方式来实现)
 
 
 

generatorConfig.xml:

Mybatis Generator的model生成中文注释,支持oracle和mysql(通过实现CommentGenerator接口的方法来实现)
maven手动安装jar包到本地仓库,以ojdbc6为例,
 
Mybatis Generator的model生成中文注释,支持oracle和mysql(通过修改源码的方式来实现)
 
 
 
<?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 >
        <!-- 指定生成的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:UsersAdministratorDesktop">
            <property name="enableSubPackages" value="true" />
            <property name="trimStrings" value="true" />
        </javaModelGenerator>

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

        <!-- mapper class -->
        <javaClientGenerator type="XMLMAPPER"
            targetPackage="dao" targetProject="C:UsersAdministratorDesktop">
            <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>
Mybatis Generator的model生成中文注释,支持oracle和mysql(通过实现CommentGenerator接口的方法来实现)
maven手动安装jar包到本地仓库,以ojdbc6为例,
 
Mybatis Generator的model生成中文注释,支持oracle和mysql(通过修改源码的方式来实现)
 
 
 

这里使用的是默认的就不用指定commentGenerator节点的type属性了.生成后的model效果如下:

Mybatis Generator的model生成中文注释,支持oracle和mysql(通过实现CommentGenerator接口的方法来实现)
maven手动安装jar包到本地仓库,以ojdbc6为例,
 
Mybatis Generator的model生成中文注释,支持oracle和mysql(通过修改源码的方式来实现)
 
 
 

生成好的工具下载:

MyGenerator.rar

源码下载:

MyGenerator-source.rar