欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

使用MyBatis-Generator如何自动生成映射文件

程序员文章站 2022-06-15 13:25:30
目录mybatis-generator自动生成映射文件1、使用cmd命令方式生成2、使用maven方式生成3、如果开发工具为eclipse自动生成mybatis映射文件工具问题mybatis-gene...

mybatis-generator自动生成映射文件

生成的方式一共有三种

1、使用cmd命令方式生成

首先在generator.xml中指定数据库驱动包位置,然后在mybatis-generator-core-1.3.1包下创建一个src文件夹(否则生成的文件没地方放)

生产的mapper.xml文件与domain类放在一个报下面(否则无法映射)

e:\>java -jar e:\mybatis-generator-core-1.3.1\lib\mybatis-generator-core-1.3.1.j
ar -configfile e:\mybatis-generator-core-1.3.1\generator.xml -overwrite

generator.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>
        <!-- 数据库驱动位置 -->
    <classpathentry location="e:\mybatis-generator-core-1.3.1\mysql-connector-java-5.0.8-bin.jar" />
    <context id="db2tables" targetruntime="mybatis3">
    <commentgenerator>
        <property name="suppressallcomments" value="true" />
    </commentgenerator>
        <!-- 数据库的url、用户名、密码 -->
    <jdbcconnection driverclass="com.mysql.jdbc.driver" connectionurl="jdbc:mysql://localhost:3306/dbo" userid="root" password="123456">
    </jdbcconnection>
    <javatyperesolver >
        <property name="forcebigdecimals" value="false" />
    </javatyperesolver>
        <!-- 生成模型的包名和位置 -->
    <javamodelgenerator targetpackage="com.paywing.domain" targetproject="e:\mybatis-generator-core-1.3.1\src">
        <property name="enablesubpackages" value="true" />
        <property name="trimstrings" value="true" />
    </javamodelgenerator>
        <!-- 生成的映射文件包名和位置 -->
    <sqlmapgenerator targetpackage="com.paywing.mapping"  targetproject="e:\mybatis-generator-core-1.3.1\src">
        <property name="enablesubpackages" value="true" />
    </sqlmapgenerator>
        <!-- 生成dao的包名和位置 -->
    <javaclientgenerator type="xmlmapper" targetpackage="com.paywing.dao"  targetproject="e:\mybatis-generator-core-1.3.1\src">
        <property name="enablesubpackages" value="true" />
    </javaclientgenerator>
        <!-- 生成那些表 tablename表名,domainobjectname应于数据库表的javabean类名-->
        <table tablename="tb_bookinfo" domainobjectname="tb_bookinfo" enablecountbyexample="false" enableupdatebyexample="false" enabledeletebyexample="false" enableselectbyexample="false" selectbyexamplequeryid="false"/>
        <table tablename="tb_booktype" domainobjectname="tb_booktype" enablecountbyexample="false" enableupdatebyexample="false" enabledeletebyexample="false" enableselectbyexample="false" selectbyexamplequeryid="false" />  
    </context>
</generatorconfiguration>

2、使用maven方式生成

(这种方式在各个工具下都能使用,推荐使用这种方式)

generator.properties

    #工程src路径 这里如果是maven启动的话去掉mybatis/ 
project=mybatis/src/main/java
    #工程存放mapper.xml路径  这里如果是maven启动的话去掉mybatis/ 
resource=mybatis/src/main/resources
package_domain=com.practice.mybatis.entity
package_mapper=mappers.test
package_dao=com.practice.mybatis.dao
package_service=com.practice.mybatis.service
    #\u6307\u5b9a\u6570\u636e\u8fde\u63a5\u9a71\u52a8jar\u5730\u5740  
classpath=d:/maven_lib/mysql/mysql-connector-java/5.1.30/mysql-connector-java-5.1.30.jar 
jdbc.driver=com.mysql.jdbc.driver
jdbc.url=jdbc:mysql://localhost:3306/test?useunicode=true&characterencoding=utf-8
jdbc.user=root
jdbc.password=123456

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>
        <!-- 引入配置文件 -->  
    <properties resource="generator.properties"/> 
        <!-- 数据库驱动位置 --> 
    <classpathentry location="${classpath}" />
        <!-- 一个数据库一个context, targetruntime:此属性用于指定生成的代码的运行时环境 ,mybatis3:*这是默认值*,mybatis3simple不生成example查询(避免后面一个一个表设置)     defaultmodeltype:如何生成实体类,flat表示为每一张表生成一个实体类,推荐使用--> 
<context id="mysqltables" targetruntime="com.practice.mybatis.tkmybatis3impl" defaultmodeltype="flat">
        <!-- 注释  type表示自定义注释-->
    <commentgenerator type="com.practice.mybatis.mycommentgenerator">
        <!-- 生成文件的编码 (eclipse插件的时候这里并没有什么卵用,需要在eclipse根目录的eclipse.ini最后添加 -dfile.encoding=utf-8  )-->
        <property name="javafileencoding" value="utf-8"/>
        <!-- 是否取消注释 -->
        <property name="suppressallcomments" value="false" />
        <property name="addremarkcomments" value="true"/>
        <!-- 是否生成注释代时间戳 -->
        <property name="suppressdate" value="true" />
        <!-- 当表名或者字段名为sql关键字的时候,可以设置该属性为true,mbg会自动给表名或字段名添加**分隔符**  -->    
        <property name="autodelimitkeywords" value="true"></property>
        <!-- 由于beginningdelimiter和endingdelimiter的默认值为双引号("),在mysql中不能这么写,所以还要将这两个默认值改为**反单引号(`)** -->
        <property name="beginningdelimiter" value="`"/>
        <property name="endingdelimiter" value="`"/>  
    </commentgenerator>
        <!-- 数据库的url、用户名、密码 --> 
    <jdbcconnection driverclass="${jdbc.driver}" 
        connectionurl="${jdbc.url}" 
        userid="${jdbc.user}" 
        password="${jdbc.password}">
    </jdbcconnection>
        <!-- 类型转换 --> 
    <javatyperesolver >
        <!-- 是否使用bigdecimal, false可自动转化以下类型(long, integer, short, etc.) -->  
        <property name="forcebigdecimals" value="false" />
    </javatyperesolver>
        <!-- 生成模型的包名和位置 -->
    <javamodelgenerator targetpackage="${package_domain}" targetproject="${project}">
        <!-- 是否在当前路径下新加一层schema,eg:fase路径com.goshop.domain", true:com.goshop.domain".[schemaname] -->
        <property name="enablesubpackages" value="false" />
        <!-- 是否针对string类型的字段在set的时候进行trim调用 -->
        <property name="trimstrings" value="true" />
    </javamodelgenerator>
        <!-- 生成的映射文件包名和位置 -->
    <sqlmapgenerator targetpackage="${package_mapper}"  targetproject="${resource}">
        <!-- 是否在当前路径下新加一层schema,eg:fase路径com.goshop.domain", true:com.goshop.domain".[schemaname] -->
        <property name="enablesubpackages" value="true" />
    </sqlmapgenerator>
        <!-- 生成dao的包名和位置 type 1、annotatedmapper注解形式 2、xmlmapper xml配置文件形式-->
    <javaclientgenerator type="xmlmapper" targetpackage="${package_dao}"  targetproject="${project}">
        <property name="enablesubpackages" value="true" />
    </javaclientgenerator>
        <!-- 生成那些表 tablename表名 mappername 生成dao的名称,domainobjectname应于数据库表的javabean类名,enable*byexample是否生成 example类 -->
        <!-- <table tablename="sys_user" domainobjectname="sysuser" enablecountbyexample="false" enableupdatebyexample="false" enabledeletebyexample="false" enableselectbyexample="false" selectbyexamplequeryid="false"/> -->
            <!-- 忽略列,不生成bean 字段   
            <ignorecolumn column="fred" />-->  
            <!-- 指定列的java数据类型   
            <columnoverride column="long_varchar_field" jdbctype="varchar" />-->  
        <table tablename="%" mappername="{0}dao">
            <columnoverride column="remarks" jdbctype="varchar" />
        </table>
</context>
</generatorconfiguration>

注意:这里由于需要自定义中文注释,因此需要修改源码,这里附上修改后的代码。

mycommentgenerator.java

这个文件是关于注释的部分,只需要实现commentgenerator接口就可以。

/**
 *    copyright 2006-2016 the original author or authors.
 *
 *    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 com.practice.mybatis;
import java.text.simpledateformat;
import java.util.date;
import java.util.list;
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.fullyqualifiedjavatype;
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.java.toplevelclass;
import org.mybatis.generator.api.dom.xml.textelement;
import org.mybatis.generator.api.dom.xml.xmlelement;
import org.mybatis.generator.config.mergeconstants;
import org.mybatis.generator.config.propertyregistry;
import org.mybatis.generator.internal.util.stringutility;
/**
 * 修改mybatis generator 生成的所有注释的文档
 *
 * @author wl
 */
public class mycommentgenerator implements commentgenerator {
    /** the properties. */
    private properties properties;
    /** the suppress date. */
    private boolean suppressdate;
    /** the suppress all comments. */
    private boolean suppressallcomments;
    /** the addition of table remark's comments.
     * if suppressallcomments is true, this option is ignored*/
    private boolean addremarkcomments;
    private simpledateformat dateformat;
    /**
     * instantiates a new default comment generator.
     */
    public mycommentgenerator() {
        super();
        properties = new properties();
        suppressdate = false;
        suppressallcomments = false;
        addremarkcomments = false;
    }
    /* (non-javadoc)
     * @see org.mybatis.generator.api.commentgenerator#addjavafilecomment(org.mybatis.generator.api.dom.java.compilationunit)
     */
    public void addjavafilecomment(final compilationunit compilationunit) {
        // add no file level comments by default
    }
    /**
     * adds a suitable comment to warn users that the element was generated, and when it was generated.
     *
     * @param xmlelement
     *            the xml element
     */
    public void addcomment(final xmlelement xmlelement) {
        if (suppressallcomments) {
            return;
        }
        xmlelement.addelement(new textelement("<!--")); //$non-nls-1$
        final stringbuilder sb = new stringbuilder();
//        sb.append("  warning - "); //$non-nls-1$
        sb.append(mergeconstants.new_element_tag);
        xmlelement.addelement(new textelement(sb.tostring()));
//        xmlelement
//                .addelement(new textelement(
//                        "  this element is automatically generated by mybatis generator, do not modify.")); //$non-nls-1$
//
//        final string s = getdatestring();
//        if (s != null) {
//            sb.setlength(0);
//            sb.append("  this element was generated on "); //$non-nls-1$
//            sb.append(s);
//            sb.append('.');
//            xmlelement.addelement(new textelement(sb.tostring()));
//        }
        xmlelement.addelement(new textelement("-->")); //$non-nls-1$
    }
    /* (non-javadoc)
     * @see org.mybatis.generator.api.commentgenerator#addrootcomment(org.mybatis.generator.api.dom.xml.xmlelement)
     */
    public void addrootcomment(final xmlelement rootelement) {
        // add no document level comments by default
    }
    /* (non-javadoc)
     * @see org.mybatis.generator.api.commentgenerator#addconfigurationproperties(java.util.properties)
     */
    public void addconfigurationproperties(final 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));
        addremarkcomments = istrue(properties
                .getproperty(propertyregistry.comment_generator_add_remark_comments));
        final string dateformatstring = properties.getproperty(propertyregistry.comment_generator_date_format);
        if (stringutility.stringhasvalue(dateformatstring)) {
            dateformat = new simpledateformat(dateformatstring);
        }
    }
       public static boolean istrue(string s) {
            return "true".equalsignorecase(s); //$non-nls-1$
       }
    /**
     * 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
     * @param markasdonotdelete
     *            the mark as do not delete
     */
    protected void addjavadoctag(final javaelement javaelement,
            final boolean markasdonotdelete) {
        javaelement.addjavadocline(" *"); //$non-nls-1$
        final stringbuilder sb = new stringbuilder();
        sb.append(" * "); //$non-nls-1$
        sb.append(mergeconstants.new_element_tag);
        if (markasdonotdelete) {
            sb.append(" do_not_delete_during_merge"); //$non-nls-1$
        }
        final 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() {
        if (suppressdate) {
            return null;
        } else if (dateformat != null) {
            return dateformat.format(new date());
        } else {
            return new date().tostring();
        }
    }
    /* (non-javadoc)
     * @see org.mybatis.generator.api.commentgenerator#addclasscomment(org.mybatis.generator.api.dom.java.innerclass, org.mybatis.generator.api.introspectedtable)
     */
    public void addclasscomment(final innerclass innerclass,
            final introspectedtable introspectedtable) {
        if (suppressallcomments) {
            return;
        }
        final stringbuilder sb = new stringbuilder();
        innerclass.addjavadocline("/**"); //$non-nls-1$
        innerclass
                .addjavadocline(" * this class was generated by mybatis generator."); //$non-nls-1$
        sb.append(" * this class corresponds to the database table "); //$non-nls-1$
        sb.append(introspectedtable.getfullyqualifiedtable());
        innerclass.addjavadocline(sb.tostring());
        addjavadoctag(innerclass, false);
        innerclass.addjavadocline(" */"); //$non-nls-1$
    }
    /* (non-javadoc)
     * @see org.mybatis.generator.api.commentgenerator#addtoplevelclasscomment(org.mybatis.generator.api.dom.java.toplevelclass, org.mybatis.generator.api.introspectedtable)
     */
    public void addmodelclasscomment(final toplevelclass toplevelclass,
            final introspectedtable introspectedtable) {
        if (suppressallcomments  || !addremarkcomments) {
            return;
        }
        final stringbuilder sb = new stringbuilder();
        toplevelclass.addjavadocline("/**"); //$non-nls-1$
        final string remarks = introspectedtable.getremarks();
        if (addremarkcomments && stringutility.stringhasvalue(remarks)) {
            toplevelclass.addjavadocline(" * database table remarks:");
            final string[] remarklines = remarks.split(system.getproperty("line.separator"));  //$non-nls-1$
            for (string remarkline : remarklines) {
                toplevelclass.addjavadocline(" *   " + remarkline);  //$non-nls-1$
            }
        }
//        toplevelclass.addjavadocline(" *"); //$non-nls-1$
//        toplevelclass
//                .addjavadocline(" * this class was generated by mybatis generator."); //$non-nls-1$
//        sb.append(" * this class corresponds to the database table "); //$non-nls-1$
        sb.append(" * 对应于数据库表  "); //$non-nls-1$
        sb.append(introspectedtable.getfullyqualifiedtable());
        toplevelclass.addjavadocline(sb.tostring());
        addjavadoctag(toplevelclass, true);
        toplevelclass.addjavadocline(" */"); //$non-nls-1$
    }
    /* (non-javadoc)
     * @see org.mybatis.generator.api.commentgenerator#addenumcomment(org.mybatis.generator.api.dom.java.innerenum, org.mybatis.generator.api.introspectedtable)
     */
    public void addenumcomment(final innerenum innerenum,
            final introspectedtable introspectedtable) {
        if (suppressallcomments) {
            return;
        }
//        stringbuilder sb = new stringbuilder();
        innerenum.addjavadocline("/**"); //$non-nls-1$
//        innerenum
//                .addjavadocline(" * this enum was generated by mybatis generator."); //$non-nls-1$
//
//        sb.append(" * this enum corresponds to the database table "); //$non-nls-1$
//        sb.append(introspectedtable.getfullyqualifiedtable());
//        innerenum.addjavadocline(sb.tostring());
        addjavadoctag(innerenum, false);
        innerenum.addjavadocline(" */"); //$non-nls-1$
    }
    /* (non-javadoc)
     * @see org.mybatis.generator.api.commentgenerator#addfieldcomment(org.mybatis.generator.api.dom.java.field, org.mybatis.generator.api.introspectedtable, org.mybatis.generator.api.introspectedcolumn)
     */
    public void addfieldcomment(final field field,
            final introspectedtable introspectedtable,
            final introspectedcolumn introspectedcolumn) {
        if (suppressallcomments) {
            return;
        }
        field.addjavadocline("/**"); //$non-nls-1$
        string remarks = introspectedcolumn.getremarks();
        if (addremarkcomments && stringutility.stringhasvalue(remarks)) {
            field.addjavadocline(" * database column remarks:");
            final string[] remarklines = remarks.split(system.getproperty("line.separator"));  //$non-nls-1$
            for (string remarkline : remarklines) {
                field.addjavadocline(" *   " + remarkline);  //$non-nls-1$
            }
        }
//        field.addjavadocline(" *"); //$non-nls-1$
        stringbuilder sb = new stringbuilder();
        sb.append(" * "+introspectedtable.getfullyqualifiedtable());
        sb.append('.');
        sb.append(introspectedcolumn.getactualcolumnname());
        sb.append(introspectedcolumn.getremarks()==null ? " " : " "+introspectedcolumn.getremarks());
        field.addjavadocline(sb.tostring());
        addjavadoctag(field, false);
        field.addjavadocline(" */"); //$non-nls-1$
    }
    /* (non-javadoc)
     * @see org.mybatis.generator.api.commentgenerator#addfieldcomment(org.mybatis.generator.api.dom.java.field, org.mybatis.generator.api.introspectedtable)
     */
    public void addfieldcomment(final field field, final introspectedtable introspectedtable) {
        if (suppressallcomments) {
            return;
        }
        final stringbuilder sb = new stringbuilder();
        field.addjavadocline("/**"); //$non-nls-1$
        field
                .addjavadocline(" * this field was generated by mybatis generator."); //$non-nls-1$
        sb.append(" * this field corresponds to the database table "); //$non-nls-1$
        sb.append(introspectedtable.getfullyqualifiedtable());
        field.addjavadocline(sb.tostring());
        addjavadoctag(field, false);
        field.addjavadocline(" */"); //$non-nls-1$
    }
    /* (non-javadoc)
     * @see org.mybatis.generator.api.commentgenerator#addgeneralmethodcomment(org.mybatis.generator.api.dom.java.method, org.mybatis.generator.api.introspectedtable)
     */
    public void addgeneralmethodcomment(final method method,
            final introspectedtable introspectedtable) {
        if (suppressallcomments) {
            return;
        }
        stringbuilder sb = new stringbuilder();
        method.addjavadocline("/**"); //$non-nls-1$
//        method
//                .addjavadocline(" * this method was generated by mybatis generator."); //$non-nls-1$
//
//        sb.append(" * this method corresponds to the database table "); //$non-nls-1$
//        sb.append(introspectedtable.getfullyqualifiedtable());
        list<parameter> parameters =  method.getparameters();
        for (parameter parameter : parameters) {
            sb.append(" *@param  ");
            sb.append(parameter.getname());
            sb.append(".");
            method.addjavadocline(sb.tostring());
            sb.delete(0, sb.length());
        }
        method.addjavadocline(method.getreturntype().getshortname()==null ? ""
                :" *@return "+method.getreturntype().getshortname()+".");
        addjavadoctag(method, false);
        method.addjavadocline(" */"); //$non-nls-1$
    }
    /* (non-javadoc)
     * @see org.mybatis.generator.api.commentgenerator#addgettercomment(org.mybatis.generator.api.dom.java.method, org.mybatis.generator.api.introspectedtable, org.mybatis.generator.api.introspectedcolumn)
     */
    public void addgettercomment(final method method,
            final introspectedtable introspectedtable,
            final introspectedcolumn introspectedcolumn) {
        if (suppressallcomments) {
            return;
        }
        stringbuilder sb = new stringbuilder();
        method.addjavadocline("/**"); //$non-nls-1$
//        method
//                .addjavadocline(" * this method was generated by mybatis generator."); //$non-nls-1$
//
//        sb.append(" * this method returns the value of the database column "); //$non-nls-1$
//        sb.append(introspectedtable.getfullyqualifiedtable());
//        sb.append('.');
//        sb.append(introspectedcolumn.getactualcolumnname());
//        method.addjavadocline(sb.tostring());
//
//        method.addjavadocline(" *"); //$non-nls-1$
//
//        sb.setlength(0);
//        sb.append(" * @return the value of "); //$non-nls-1$
//        sb.append(introspectedtable.getfullyqualifiedtable());
//        sb.append('.');
//        sb.append(introspectedcolumn.getactualcolumnname());
        sb.append(" * @return "+(
                introspectedcolumn.getactualcolumnname()==null ? "":introspectedcolumn.getactualcolumnname()));
        sb.append(" .");
        method.addjavadocline(sb.tostring());
        addjavadoctag(method, false);
        method.addjavadocline(" */"); //$non-nls-1$
    }
    /* (non-javadoc)
     * @see org.mybatis.generator.api.commentgenerator#addsettercomment(org.mybatis.generator.api.dom.java.method, org.mybatis.generator.api.introspectedtable, org.mybatis.generator.api.introspectedcolumn)
     */
    public void addsettercomment(final method method,
            final introspectedtable introspectedtable,
            final introspectedcolumn introspectedcolumn) {
        if (suppressallcomments) {
            return;
        }
        stringbuilder sb = new stringbuilder();
        method.addjavadocline("/**"); //$non-nls-1$
//        method
//                .addjavadocline(" * this method was generated by mybatis generator."); //$non-nls-1$
//
//        sb.append(" * this method sets the value of the database column "); //$non-nls-1$
//        sb.append(introspectedtable.getfullyqualifiedtable());
//        sb.append('.');
//        sb.append(introspectedcolumn.getactualcolumnname());
//        method.addjavadocline(sb.tostring());
//
//        method.addjavadocline(" *"); //$non-nls-1$
//
        parameter parm = method.getparameters().get(0);
        sb.setlength(0);
        sb.append(" * @param "); //$non-nls-1$
        sb.append(parm.getname());
        sb.append((introspectedcolumn.getremarks()==null ? " " : "  "+introspectedcolumn.getremarks()));
        sb.append(".");
//        sb.append(" the value for "); //$non-nls-1$
//        sb.append(introspectedtable.getfullyqualifiedtable());
//        sb.append('.');
//        sb.append(introspectedcolumn.getactualcolumnname());
        method.addjavadocline(sb.tostring());
        addjavadoctag(method, false);
        method.addjavadocline(" */"); //$non-nls-1$
    }
    /* (non-javadoc)
     * @see org.mybatis.generator.api.commentgenerator#addclasscomment(org.mybatis.generator.api.dom.java.innerclass, org.mybatis.generator.api.introspectedtable, boolean)
     */
    public void addclasscomment(final innerclass innerclass,
            final introspectedtable introspectedtable, final boolean markasdonotdelete) {
        if (suppressallcomments) {
            return;
        }
        final stringbuilder sb = new stringbuilder();
        innerclass.addjavadocline("/**"); //$non-nls-1$
        innerclass
                .addjavadocline(" * this class was generated by mybatis generator."); //$non-nls-1$
        sb.append(" * this class corresponds to the database table "); //$non-nls-1$
        sb.append(introspectedtable.getfullyqualifiedtable());
        innerclass.addjavadocline(sb.tostring());
        addjavadoctag(innerclass, markasdonotdelete);
        innerclass.addjavadocline(" */"); //$non-nls-1$
    }
}

 1.3.4 版本以后,mbg 在元素上提供了一个mappername 的属性,可以设置生成的 mapper 名字。

但是因为 tablename 属性支持通配符 %,在这种情况下就不能使用mappername属性设置了。为了解决这种情况,提供了一个插件可以用于通配符情况下的配置。

package com.practice.mybatis;
import java.text.messageformat;
import org.mybatis.generator.codegen.mybatis3.introspectedtablemybatis3simpleimpl;
/**
 * @author win7
 *生成dao后缀
 */
public class tkmybatis3impl extends introspectedtablemybatis3simpleimpl  {
    @override
    protected string calculatemybatis3xmlmapperfilename() {
        final stringbuilder sb = new stringbuilder();
        if (stringhasvalue(tableconfiguration.getmappername())) {
            string mappername = tableconfiguration.getmappername();
            final int ind = mappername.lastindexof('.');
            if (ind != -1) {
                mappername = mappername.substring(ind + 1);
            }
            //支持mappername = "{0}dao" 等用法
            sb.append(messageformat.format(mappername, fullyqualifiedtable.getdomainobjectname()));
            sb.append(".xml"); //$non-nls-1$
        } else {
            sb.append(fullyqualifiedtable.getdomainobjectname());
            sb.append("mapper.xml"); //$non-nls-1$
        }
        return sb.tostring();
    }
    public static boolean stringhasvalue(final string s) {
        return s != null && s.length() > 0;
    }
    @override
    protected void calculatejavaclientattributes() {
        if (context.getjavaclientgeneratorconfiguration() == null) {
            return;
        }
        final stringbuilder sb = new stringbuilder();
        sb.append(calculatejavaclientimplementationpackage());
        sb.append('.');
        sb.append(fullyqualifiedtable.getdomainobjectname());
        sb.append("daoimpl"); //$non-nls-1$
        setdaoimplementationtype(sb.tostring());
        sb.setlength(0);
        sb.append(calculatejavaclientinterfacepackage());
        sb.append('.');
        sb.append(fullyqualifiedtable.getdomainobjectname());
        sb.append("dao"); //$non-nls-1$
        setdaointerfacetype(sb.tostring());
        sb.setlength(0);
        sb.append(calculatejavaclientinterfacepackage());
        sb.append('.');
        if (stringhasvalue(tableconfiguration.getmappername())) {
            //支持mappername = "{0}dao" 等用法
            sb.append(messageformat.format(tableconfiguration.getmappername(), fullyqualifiedtable.getdomainobjectname()));
        } else {
            sb.append(fullyqualifiedtable.getdomainobjectname());
            sb.append("mapper"); //$non-nls-1$
        }
        setmybatis3javamappertype(sb.tostring());
        sb.setlength(0);
        sb.append(calculatejavaclientinterfacepackage());
        sb.append('.');
        if (stringhasvalue(tableconfiguration.getsqlprovidername())) {
            //支持mappername = "{0}sqlprovider" 等用法
            sb.append(messageformat.format(tableconfiguration.getsqlprovidername(), fullyqualifiedtable.getdomainobjectname()));
        } else {
            sb.append(fullyqualifiedtable.getdomainobjectname());
            sb.append("sqlprovider"); //$non-nls-1$
        }
        setmybatis3sqlprovidertype(sb.tostring());
    }
}

以上是所有的配置,下面设置maven启动

idea下(wl.jar是需要添加中文注释所修改的源码后打的jar)

pom.xml

            <plugin>
                <groupid>org.mybatis.generator</groupid>
                <artifactid>mybatis-generator-maven-plugin</artifactid>
                <version>1.3.5</version>
                <dependencies>
                    <dependency>
                        <groupid>mysql</groupid>
                        <artifactid>mysql-connector-java</artifactid>
                        <version>5.1.30</version>
                    </dependency>
                    <dependency>
                        <groupid>mygenerator</groupid>
                        <artifactid>com.mybatis.generator.wl</artifactid>
                        <version>1.0</version>
                        <scope>system</scope>
                        <systempath>${basedir}\src\main\webapp\web-inf\lib\com.mybatis.generator.wl.jar</systempath>
                    </dependency>
                </dependencies>
                <configuration>
                    <!--配置文件的路径-->
                    <configurationfile>${basedir}/src/main/resources/generatorconfig.xml</configurationfile>
                    <!--允许移动生成的文件-->
                    <verbose>true</verbose>
                    <!--允许覆盖生成的文件-->
                    <overwrite>true</overwrite>
                </configuration>
            </plugin>

maven配置

command line:

mybatis-generator:generate

eclipse下

pom.xml配置同上

goals

mybatis-generator:generate

注意:maven方式启动的话,上面geterator.properties里的project与resource 需要去掉项目名称。

generatorconfig.xml里面targetruntime与自定义注释的java文件配置的是修改完源码导入到项目中jar的路径。

3、如果开发工具为eclipse

可以安装generator的插件,然后生成generatorconfig.xml进行修改配置。

最后通过右键就可以运行。

自动生成mybatis映射文件工具

问题

总是自己写crud的操作太烦躁了,还不如直接自动生成一下curd的操作了,自己写查询的操作,接下来就提供给一个很好用的快捷生成mapper和mapper映射文件的工具类,将这个工具xml文件直接放到resource文件夹下就可以了!!

<build>
        <finalname>com.jimi.house</finalname>
        <plugins>
            <plugin>
                <groupid>org.apache.maven.plugins</groupid>
                <artifactid>maven-compiler-plugin</artifactid>
                <version>3.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <compilerarguments>
                        <verbose/>
                        <bootclasspath>${java.home}/lib/rt.jar;${java.home}/lib/jce.jar</bootclasspath>
                    </compilerarguments>
                    <!--<encoding>utf-8</encoding>-->
                </configuration>
            </plugin>
 
            <plugin>
                <groupid>org.mybatis.generator</groupid>
                <artifactid>mybatis-generator-maven-plugin</artifactid>
                <version>1.3.2</version>
                <configuration>
                    <verbose>true</verbose>
                    <overwrite>true</overwrite>
                </configuration>
            </plugin>
        </plugins>
    </build>
<?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>
    <!-- 数据库驱动:选择你的本地硬盘上面的数据库驱动包-->
    <classpathentry  location="d:/apache-maven-3.5.0/repo/mysql/mysql-connector-java/5.1.35/mysql-connector-java-5.1.35.jar"/>
    <context id="db2tables"  targetruntime="mybatis3">
        <commentgenerator>
            <property name="suppressdate" value="true"/>
            <!-- 是否去除自动生成的注释 true:是 : false:否 -->
            <property name="suppressallcomments" value="true"/>
        </commentgenerator>
        <!--数据库链接url,用户名、密码 -->
        <jdbcconnection driverclass="com.mysql.jdbc.driver" connectionurl="jdbc:mysql://localhost:3306/identity" userid="root" password="root">
        </jdbcconnection>
        <javatyperesolver>
            <property name="forcebigdecimals" value="false"/>
        </javatyperesolver>
        <!-- 生成模型的包名和位置-->
        <javamodelgenerator targetpackage="com.chaimao.newparent.entity" targetproject="src/main/java">
            <property name="enablesubpackages" value="true"/>
            <property name="trimstrings" value="true"/>
        </javamodelgenerator>
        <!-- 生成映射文件的包名和位置-->
        <sqlmapgenerator targetpackage="mapper" targetproject="src/main/resources">
            <property name="enablesubpackages" value="true"/>
        </sqlmapgenerator>
        <!-- 生成dao的包名和位置-->
        <javaclientgenerator type="xmlmapper" targetpackage="com.chaimao.newparent.mapper" targetproject="src/main/java">
            <property name="enablesubpackages" value="true"/>
        </javaclientgenerator>
        <!-- 要生成的表 tablename是数据库中的表名或视图名 domainobjectname是实体类名-->
        <table tablename="identity_record" domainobjectname="identityrecord" enablecountbyexample="false" enableupdatebyexample="false" enabledeletebyexample="false" enableselectbyexample="false" selectbyexamplequeryid="false"></table>
    </context>
</generatorconfiguration>

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。