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,以下是一个样本

/*
 *  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(" */");
    }
}
View Code

为了是辛辛苦苦写的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效果如下:

 

生成好的工具下载:

MyGenerator.rar

源码下载:

MyGenerator-source.rar

 

转载于:https://www.cnblogs.com/NieXiaoHui/p/6100895.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: MyBatis Generator 是一个可以自动化生成MyBatis代码的工具,包括 Mapper 接口、Mapper XML 文件以及 POJO 类等。如果你想要生成 Mapper XML 文件,可以按照以下步骤进行操作: 1. 配置 MyBatis Generator 插件:在 pom.xml 文件中添加以下依赖: ```xml <dependency> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-core</artifactId> <version>1.4.0</version> </dependency> ``` 2. 编写 MyBatis Generator 配置文件:创建一个名为 generatorConfig.xml 的文件,并按照以下格式进行配置: ```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"> <!-- 配置数据库连接信息 --> <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/test" userId="root" password="root"> </jdbcConnection> <!-- 配置生成的 Java 模型类的包名和位置 --> <javaModelGenerator targetPackage="com.example.model" targetProject="src/main/java"> <property name="enableSubPackages" value="true" /> <property name="trimStrings" value="true" /> </javaModelGenerator> <!-- 配置生成的 Mapper 接口的包名和位置 --> <sqlMapGenerator targetPackage="com.example.mapper" targetProject="src/main/resources"> <property name="enableSubPackages" value="true" /> </sqlMapGenerator> <!-- 配置生成的 Mapper XML 文件的位置 --> <javaClientGenerator type="XMLMAPPER" targetPackage="com.example.mapper" targetProject="src/main/java"> <property name="enableSubPackages" value="true" /> </javaClientGenerator> <!-- 配置要生成的表 --> <table tableName="user" domainObjectName="User" /> </context> </generatorConfiguration> ``` 其中,`jdbcConnection` 标签用于配置数据库连接信息,`javaModelGenerator` 标签用于配置生成的 Java 模型类的包名和位置, `sqlMapGenerator` 标签用于配置生成的 Mapper 接口的包名和位置,`javaClientGenerator` 标签用于配置生成的 Mapper XML 文件的位置,`table` 标签用于配置要生成的表。 3. 运行 MyBatis Generator:在工程根目录下执行以下命令: ``` mvn mybatis-generator:generate ``` 执行命令后,MyBatis Generator 将自动生成 Mapper XML 文件,并放置在 `target/generated-sources/mybatis-generator` 目录下。 注意:在执行命令之前,需要先将 Maven 的 settings.xml 文件中的本地仓库地址修改为你自己的仓库地址,否则可能会出现找不到 MyBatis Generator 插件的情况。 ### 回答2: MyBatis Generator是一个在Java项目中自动生成MyBatis数据库访问层代码的工具。它能够根据数据库表结构自动生成包含增删改查等基本方法的Mapper接口和对应的XML映射文件。 生成Mapper接口和XML映射文件的过程非常简单。首先需要配置MyBatis Generator生成规则,配置文件中包括数据库连接信息以及要生成的表名等。其次,可以使用命令行或者Maven插件来执行生成命令,工具会连接数据库读取表信息,并据此生成对应的Mapper接口和XML映射文件。 生成的Mapper接口中包含了常见的数据库操作方法,如插入insert、删除delete、更新update和查询select。这些方法会在对应的XML映射文件中被实现,通过SQL语句与数据库进行交互。可以根据需要自定义SQL语句,也可以使用MyBatis提供的动态SQL特性来灵活地构建查询条件。 生成的XML映射文件中,会将Mapper接口中定义的方法与对应的SQL语句进行映射。映射时需要指定SQL语句的类型,如insert、delete、update或select,并在对应的标签中编写具体的SQL语句。可以使用占位符来引用Mapper接口方法中的参数,从而实现动态SQL的拼接。 总之,使用MyBatis Generator可以方便地自动生成Mapper接口和XML映射文件,减少了手动编写代码的工作量,提高了开发效率。同时,生成的代码结构清晰,易于维护和扩展。 ### 回答3: MyBatis Generator是一个用于自动生成持久层代码的工具,它可以根据数据库表结构自动生成代码,包括mapper.xml文件中的方法。 MyBatis Generator生成mapper.xml文件中的方法需要指定数据表的信息,比如表名、列名、数据类型等。通常情况下,我们需要先创建一个配置文件,指定数据库的连接信息和要生成代码的目标文件路径等。 在配置文件中,可以通过配置表名的规则、列名的规则以及其他定制化的配置项,来指定生成代码的方式和风格。配置完成后,执行生成器程序,它会根据配置文件中的规则和信息自动读取数据库表结构,并生成对应的mapper.xml文件。 生成的mapper.xml文件会包含CRUD操作的基础方法,比如插入、删除、更新、查询等,这些方法的具体实现会根据数据库表结构自动生成生成的方法会根据表结构的主键、索引等信息生成对应的条件查询方法,方便根据特定的条件进行查询操作。 此外,MyBatis Generator还可以生成动态SQL查询的方法,可以根据不同的查询条件生成不同的查询语句,方便根据不同的需求进行灵活的查询。 总而言之,通过配置文件和执行生成器程序,可以使用MyBatis Generator自动化生成mapper.xml文件中的方法,从而减少手工编写重复繁琐的代码工作,提高开发效率。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值