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

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>

以上為個人經驗,希望能給大傢一個參考,也希望大傢多多支持WalkonNet。

推薦閱讀: