使用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




        
    
    
    
        
    
        
    
    
    
        
    
        
    
        
        
    
        
    
        
    
        
    
        
    
        
        

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




          
     
         
    
         

        
    
        
        
        
        
        
        
        
            
        
        
        
          
    
         
    
    
         
    
          
        
    
        
    
        
        
        
        
    
        
    
        
        
    
        
    
        
    
        
        
              
              
        

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

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$
    }
    /* (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 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

            
                org.mybatis.generator
                mybatis-generator-maven-plugin
                1.3.5
                
                    
                        mysql
                        mysql-connector-java
                        5.1.30
                    
                    
                        mygenerator
                        com.mybatis.generator.wl
                        1.0
                        system
                        ${basedir}\src\main\webapp\WEB-INF\lib\com.mybatis.generator.wl.jar
                    
                
                
                    
                    ${basedir}/src/main/resources/generatorConfig.xml
                    
                    true
                    
                    true
                
            

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文件夹下就可以了!!


        com.jimi.house
        
            
                org.apache.maven.plugins
                maven-compiler-plugin
                3.1
                
                    1.8
                    1.8
                    
                        
                        ${java.home}/lib/rt.jar;${java.home}/lib/jce.jar
                    
                    
                
            
 
            
                org.mybatis.generator
                mybatis-generator-maven-plugin
                1.3.2
                
                    true
                    true
                
            
        
    



    
    
    
        
            
            
            
        
        
        
        
        
            
        
        
        
            
            
        
        
        
            
        
        
        
            
        
        
        

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

你可能感兴趣的:(使用MyBatis-Generator如何自动生成映射文件)