Mybatis Generator's model generates Chinese annotations that support Oracle and MySQL (implemented by implementing the Commentgenerator interface method)

Source: Internet
Author: User
Tags rar log4j

Before looking at this article, it is better to first look at the previous article by implementing the Commentgenerator interface method to implement the Chinese annotation example, because many operations and the previous article is basically consistent, so this article may be less detailed.

First of all, the last article through the implementation of some Commentgenerator interface, after all, just realize the Commentgenerator interface, the method in the inside of how to change, effective is only for the model class, and the use of people probably also found, The Addclasscomment method in the inside is known to generate comments on the class file, but no matter what we write in the implementation of this method has no effect, in fact, because MGB default is not called this method, this time if there is a need to generate a class file automatically added class document description can not be done, And if the source code on the basis of modification, it is better to do more, how to change how to change, as long as find the right place, what kind of need can write their own code to achieve.

    • First of all, I create a new MAVEN project, how to do not elaborate, the previous article has, are ready to modify the Pom.xml file, the first introduction of MBG source code, in the Pom.xml to join the dependency
<dependency>            <groupId>org.mybatis.generator</groupId>            <artifactId> mybatis-generator-core</artifactid>            <version>1.3.2</version>        </dependency>

After saving it will automatically download the Mybatis-generator-core jar package, and then we go to our local warehouse to find the location of the jar package, download the Pom.xml after the dependency can be deleted.

We will see not only the download of the jar package, the source code is also downloaded together, with the compression software to open Source,jar, copy the Org folder and all the files within its own eclipse-built Maven project, so that the MBG source code, you can also

Http://search.maven.org Search Mybatis-generator-core and then click Source.jar to download the source code directly.

    • After the first step to get the source code, copied to the project we will find that the error, because there is no dependency on the introduction of the package, the lack of log4j and ant package, added in the Pom.xml dependencies, by the way, the addition of Oracle and MySQL driver package, Oracle's local installation you can see from the previous article that there is no error when you join the project.
      <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>

The structure of our project should be this way this time.

Then it is very simple, in the source code to find Org.mybatis.generator.internal.DefaultCommentGenerator class, casually change it, DIY, the following is a sample

/* Copyright: The Apache software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * You are not a use this file except in compliance with the License. * Obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * unless required by app Licable law or agreed to in writing, software * Distributed under the License are distributed on a "as is" BASIS, * with Out 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, the element is generated, and when it was generated.    */public void addcomment (XmlElement XmlElement) {return; } public void Addrootcomment (XmlElement rootelement) {//Add No. document level comments by default Retur    N        } 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.  Wish to include the Javadoc tag-however, if you do not include the   * Javadoc Tag then the Java merge capability of the Eclipse plugin would * break. * * @param javaelement * The Java element */protected void Addjavadoctag (Javaelement javaeleme        NT, 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 could 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 (Suppressallcomme        NTS) {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 introspec        Tedcolumn) {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, IntroSpectedtable introspectedtable) {if (suppressallcomments) {return;        }//Method.addjavadocline ("/**");        Addjavadoctag (method, False);    Method.addjavadocline ("* *"); } public void Addgettercomment (method, Introspectedtable introspectedtable, Introspectedcolumn intros        Pectedcolumn) {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 ("* Description:");       Sb.append (introspectedtable.getfullyqualifiedtable () + "table entity class");        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 ("* @ creation Time:");        Sb.append (CURRENTDATESTR);        Innerclass.addjavadocline (Sb.tostring (). replace ("\ n", ""));    Innerclass.addjavadocline ("* *"); }}

In order to be hard-written addclasscomment came into force, also to find the Org.mybatis.generator.codegen.mybatis3.model.BaseRecordGenerator class, where in about 60 rows, In Commentgenerator.addjavafilecomment (Toplevelclass), add a sentence:

Commentgenerator.addclasscomment (Toplevelclass, Introspectedtable,false);

So your own method is called to, explain, carefully look at the source code, you will find the Defaultcommentgenerator class, you will find the Addclasscomment method has two, a Boolean markasdonotdelete parameter is added, One does not add, you call here if you do not add false parameters, the Defaultcommentgenerator class in the two parameters of the Addclasscomment method, in my example you will find that the method is passed the parameters are not used, Because there's a line in the real source code.

And then in the Addjavadoctag method, this is called

The invocation of the Addjavadoctag method in my example is removed, so it's useless to pass a parameter.

    • Other if you want to have any changes, to study the source code, and then manually change it, it is almost over, the rest of the work and the same as the last time, using the MVN clean Packages command into a jar package, and then in the console to use

Java-jar mybatis-generator-core-1.3.2.jar-configfile generatorconfig.xml-overwrite Command runs, Paste the complete pom.xml and generatorconfig.xml, some places and the last time there is a difference.

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> <proper Ties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> & lt;dependencies> <dependency> <groupId>com.oracle</groupId> <artifact id>ojdbc6</artifactid> <version>6.0</version> </dependency> <depend Ency> <groupId>mysql</groupId> &LT;artifactid>mysql-connector-java</artifactid> <version>5.1.9</version> </depend ency> <dependency> <groupId>log4j</groupId> <artifactid>log4j</            artifactid> <version>1.2.7</version> </dependency> <dependency> <groupId>org.apache.ant</groupId> <artifactId>ant</artifactId> <vers ion>1.9.0</version> </dependency> </dependencies> <build> <finalName> mybatis-generator-core-1.3.2</finalname> <plugins> <plugin> &LT;ARTIFAC Tid>maven-assembly-plugin</artifactid> <version>2.6</version> <confi                        Guration> <appendAssemblyId>false</appendAssemblyId> <archive> &Lt;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" > <!--Specifies the encoding of the generated Java file, which is not generated directly to the project when Chinese may be garbled--<property name= "Javafileenco Ding "value=" UTF-8 "/> <!--Oracle configuration--><!--<jdbcconnection driverclass=" Oracle.jdbc.dri Ver.            Oracledriver "connectionurl=" JDBC:ORACLE:THIN:@***:1521:ORCL "userid=" * * * "password=" * * * "> <property name= "remarksreporting" value= "true" for Oracle database ></property> </jdbcconnect                  Ion>-<!--mysql configuration-<jdbcconnection driverclass= "Com.mysql.jdbc.Driver" Connectionurl= "Jdbc:mysql://localhost:3306/bookshop" userid= "root" password= "root" &GT          <!--for MySQL database--<property name= "Useinformationschema" value= "true" ></property> </jdbcConnection> <javaTypeResolver> <property name= "forcebigdecimals" value= "Fals E "/> </javaTypeResolver> <!--dto Class---<javamodelgenerator targetpackage=" MoD El "targetproject=" C:\Users\Administrator\Desktop "> <property name=" enablesubpackages "value=" True "/> <property name=" trimstrings "value=" true "/> </javaModelGenerator> <!- -MyBatis XML file-to-<sqlmapgenerator targetpackage= "DAO" targetproject= "C:\Users\Administrator\ Desktop "> <property name=" enablesubpackages "value=" true "/> </sqlMapGenerator> &l t;! --Mapper class-to <javaclientgenerator type= "Xmlmapper" targetpackage= "DAO" targetproject= "c:\uSers\administrator\desktop "> <property name=" enablesubpackages "value=" true "/> </javaclient Generator> <!--do not generate Help Class (Exmaples)-<!--enablecountbyexample= "false" enableupdatebyexample= "FAL Se "enabledeletebyexample=" false "enableselectbyexample=" false "Selectbyexamplequeryid=" false "--& lt;! --generated table <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>

The default is not to specify the type attribute of the Commentgenerator node. The resulting model effect is as follows:

Generate Good tools to download:

Mygenerator.rar

SOURCE Download:

Mygenerator-source.rar

Mybatis Generator's model generates Chinese annotations that support Oracle and MySQL (implemented by implementing the Commentgenerator interface method)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.