mybatis-generator逆向工程

java

浏览数:264

2019-1-13

片段 1片段 2片段 3片段 4片段 5


mybatisGeneratorInit.properties

#Mybatis Generator configuration
target.project=src/main/java
target.resources=src/main/resources
#生成实体类地址
model.target.package=com.soyea.entity
#生成mapper地址
mapper.target.package=mappers
#生成dao接口地址
dao.target.package=com.soyea.mapper
#自定义comment生成器地址
my.commentGenerator.address=com.soyea.util.MyCommentGenerator
#自定义toString插件地址
my.toStringPlugin.address=com.soyea.util.MyToStringPlugin

#数据库信息
jdbc_driver=com.mysql.jdbc.Driver
jdbc_url=jdbc:mysql://localhost:3306/wechat
jdbc_user=root
jdbc_password=soyeajr        <!--mybatis逆向工程-->
        <dependency>
            <groupId>org.mybatis.generator</groupId>
            <artifactId>mybatis-generator-core</artifactId>
            <version>1.3.2</version>
        </dependency>


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="mybatis-generator/mybatisGeneratorInit.properties"/>

    <!--classPathEntry:数据库的JDBC驱动,换成你自己的驱动位置 可选 -->
    <!--<classPathEntry location="" />-->

    <!-- 一个数据库一个context -->
    <!--defaultModelType="flat" 大数据字段,不分表 -->
    <context id="MysqlTables" targetRuntime="MyBatis3" defaultModelType="flat">

        <property name="javaFileEncoding" value="utf-8"/>

        <!--<plugin type="org.mybatis.generator.plugins.SerializablePlugin" />-->
        <!--<plugin type="org.mybatis.generator.plugins.ToStringPlugin" />-->
        <!--自定义toString插件-->
        <plugin type="${my.toStringPlugin.address}"/>

        <!-- 自定义注释 -->
        <commentGenerator type="${my.commentGenerator.address}"/>

        <!--<commentGenerator>-->
        <!--<property name="suppressAllComments" value="false"/>&lt;!&ndash; 是否取消注释 &ndash;&gt;-->
        <!--&lt;!&ndash;<property name="suppressDate" value="true" /> &lt;!&ndash; 是否生成注释代时间戳&ndash;&gt;&ndash;&gt;-->
        <!--<property name="addRemarkComments" value="true" />-->
        <!--</commentGenerator>-->

        <!-- jdbc连接 -->
        <jdbcConnection driverClass="${jdbc_driver}" connectionURL="${jdbc_url}" userId="${jdbc_user}"
                        password="${jdbc_password}"/>

        <!-- 类型转换 -->
        <javaTypeResolver>
            <!-- 是否使用bigDecimal, false可自动转化以下类型(Long, Integer, Short, etc.) -->
            <property name="forceBigDecimals" value="false"/>
        </javaTypeResolver>

        <!-- 生成实体类地址 -->
        <javaModelGenerator targetPackage="${model.target.package}" targetProject="${target.project}">
            <property name="enableSubPackages" value="false"/>
            <property name="trimStrings" value="true"/>
        </javaModelGenerator>

        <!-- 生成mapxml文件 -->
        <sqlMapGenerator targetPackage="${mapper.target.package}" targetProject="${target.resources}">
            <property name="enableSubPackages" value="false"/>
        </sqlMapGenerator>
        <!-- 生成mapxml对应client,也就是接口dao -->
        <javaClientGenerator targetPackage="${dao.target.package}" targetProject="${target.project}" type="XMLMAPPER">
            <property name="enableSubPackages" value="false"/>
        </javaClientGenerator>

        <!--生成的表-->
        <table tableName="user" enableCountByExample="true" enableUpdateByExample="true" enableDeleteByExample="true"
               enableSelectByExample="true" selectByExampleQueryId="true">
            <!--<property name="useActualColumnNames" value="false" />-->
            <generatedKey column="id" sqlStatement="Mysql" identity="true"/>
        </table>

    </context>
</generatorConfiguration>


逆向工程生成器

package com.hg.util;

import org.mybatis.generator.config.Configuration;
import org.mybatis.generator.config.xml.ConfigurationParser;
import org.mybatis.generator.exception.InvalidConfigurationException;
import org.mybatis.generator.exception.XMLParserException;
import org.mybatis.generator.internal.DefaultShellCallback;

import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * 逆向工程生成器
 * Created by skh on 2018/1/10
 */
public class MyBatisGenerator {

    //根据配置文件,生成相应的model实体类,mapper接口,mapperXMl文件
    public static void main(String[] args) {
        try {
            List<String> warnings = new ArrayList<String>();
            boolean overwrite = true;
            //注意:使用绝对路径
            File configFile = new File("F:\\project\\hg-system\\src\\main\\resources\\mybatis-generator\\generatorConfig.xml");
            ConfigurationParser cp = new ConfigurationParser(warnings);
            Configuration config = cp.parseConfiguration(configFile);
            DefaultShellCallback callback = new DefaultShellCallback(overwrite);
            org.mybatis.generator.api.MyBatisGenerator myBatisGenerator = new org.mybatis.generator.api.MyBatisGenerator(config, callback, warnings);
            myBatisGenerator.generate(null);
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (InvalidConfigurationException e) {
            e.printStackTrace();
        } catch (XMLParserException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}


MyCommentGenerator

package com.hg.util;

import static org.mybatis.generator.internal.util.StringUtility.isTrue;

import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
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.MyBatisGenerator;
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.Configuration;
import org.mybatis.generator.config.MergeConstants;
import org.mybatis.generator.config.PropertyRegistry;
import org.mybatis.generator.config.xml.ConfigurationParser;
import org.mybatis.generator.exception.InvalidConfigurationException;
import org.mybatis.generator.exception.XMLParserException;
import org.mybatis.generator.internal.DefaultShellCallback;

/**
 * mybatis generator 自定义comment生成器.
 * 基于MBG 1.3.2.
 */
public class MyCommentGenerator implements CommentGenerator {

    private Properties properties;
    private Properties systemPro;
    private boolean suppressDate;
    private boolean suppressAllComments;
    private String currentDateStr;  public MyCommentGenerator() {
        super();
        properties = new Properties();
        systemPro = System.getProperties();
        suppressDate = false;
        suppressAllComments = false;
        currentDateStr = (new SimpleDateFormat("yyyy-MM-dd")).format(new Date());
    }

    public void addJavaFileComment(CompilationUnit compilationUnit) {
        // add no file level comments by default
        return;
    }

    /**
     * Adds a suitable comment to warn users that the element was generated, and
     * when it was generated.
     */
    public void addComment(XmlElement xmlElement) {
        return;
    }

    public void addRootComment(XmlElement rootElement) {
        // add no document level comments by default
        return;
    }

    public void addConfigurationProperties(Properties properties) {
        this.properties.putAll(properties);

        suppressDate = isTrue(properties.getProperty(PropertyRegistry.COMMENT_GENERATOR_SUPPRESS_DATE));

        suppressAllComments = isTrue(properties.getProperty(PropertyRegistry.COMMENT_GENERATOR_SUPPRESS_ALL_COMMENTS));
    }

    /**
     * This method adds the custom javadoc tag for. You may do nothing if you do
     * not wish to include the Javadoc tag - however, if you do not include the
     * Javadoc tag then the Java merge capability of the eclipse plugin will
     * break.
     *
     * @param javaElement
     *            the java element
     */
    protected void addJavadocTag(JavaElement javaElement, boolean markAsDoNotDelete) {
        javaElement.addJavaDocLine(" *");
        StringBuilder sb = new StringBuilder();
        sb.append(" * ");
        sb.append(MergeConstants.NEW_ELEMENT_TAG);
        if (markAsDoNotDelete) {
            sb.append(" do_not_delete_during_merge");
        }
        String s = getDateString();
        if (s != null) {
            sb.append(' ');
            sb.append(s);
        }
        javaElement.addJavaDocLine(sb.toString());
    }

    /**
     * This method returns a formated date string to include in the Javadoc tag
     * and XML comments. You may return null if you do not want the date in
     * these documentation elements.
     *
     * @return a string representing the current timestamp, or null
     */
    protected String getDateString() {
        String result = null;
        if (!suppressDate) {
            result = currentDateStr;
        }
        return result;
    }

    public void addClassComment(InnerClass innerClass, IntrospectedTable introspectedTable) {
        if (suppressAllComments) {
            return;
        }
//      StringBuilder sb = new StringBuilder();
//      innerClass.addJavaDocLine("/**");
//      sb.append(" * ");
//      sb.append(introspectedTable.getFullyQualifiedTable());
//      sb.append(" ");
//      sb.append(getDateString());
//      innerClass.addJavaDocLine(sb.toString());
//      innerClass.addJavaDocLine(" */");
    }

    public void addEnumComment(InnerEnum innerEnum, IntrospectedTable introspectedTable) {
        if (suppressAllComments) {
            return;
        }

        StringBuilder sb = new StringBuilder();

        innerEnum.addJavaDocLine("/**");
        //      addJavadocTag(innerEnum, false);
        sb.append(" * ");
        sb.append(introspectedTable.getFullyQualifiedTable());
        innerEnum.addJavaDocLine(sb.toString());
        innerEnum.addJavaDocLine(" */");
    }

    /**
     * 字段注释
     * @param field
     * @param introspectedTable
     * @param introspectedColumn
     */
    public void addFieldComment(Field field, IntrospectedTable introspectedTable,
                                IntrospectedColumn introspectedColumn) {
        if (suppressAllComments) {
            return;
        }

        StringBuilder sb = new StringBuilder();

        field.addJavaDocLine("/**");
        sb.append(" * ");
        sb.append(introspectedColumn.getRemarks());
        field.addJavaDocLine(sb.toString());
//            addJavadocTag(field, false);

        field.addJavaDocLine(" */");
    }

    public void addFieldComment(Field field, IntrospectedTable introspectedTable) {
        if (suppressAllComments) {
            return;
        }
//
//      StringBuilder sb = new StringBuilder();
//
//      field.addJavaDocLine("/**");
//      sb.append(" * ");
//      sb.append(introspectedTable.getFullyQualifiedTable());
//      System.out.println("introspectedTable.getFullyQualifiedTable = " + introspectedTable.getFullyQualifiedTable());
//      field.addJavaDocLine(sb.toString());
//      field.addJavaDocLine(" */");
    }

    public void addGeneralMethodComment(Method method, IntrospectedTable introspectedTable) {
        if (suppressAllComments) {
            return;
        }
        //      method.addJavaDocLine("/**");
        //      addJavadocTag(method, false);
        //      method.addJavaDocLine(" */");
    }

    public void addGetterComment(Method method, IntrospectedTable introspectedTable,
                                 IntrospectedColumn introspectedColumn) {
        if (suppressAllComments) {
            return;
        }

//      method.addJavaDocLine("/**");
//
//      StringBuilder sb = new StringBuilder();
//      sb.append(" * ");
//      sb.append(introspectedColumn.getRemarks());
//      method.addJavaDocLine(sb.toString());
//
//      sb.setLength(0);
//      sb.append(" * @return ");
//      sb.append(introspectedColumn.getActualColumnName());
//      sb.append(" ");
//      sb.append(introspectedColumn.getRemarks());
//      method.addJavaDocLine(sb.toString());
//
//      //      addJavadocTag(method, false);
//
//      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());
//
//      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());
//
//      //      addJavadocTag(method, false);
//
//      method.addJavaDocLine(" */");
    }

    public void addClassComment(InnerClass innerClass, IntrospectedTable introspectedTable, boolean markAsDoNotDelete) {
        if (suppressAllComments) {
            return;
        }//     StringBuilder sb = new StringBuilder();
//
//      innerClass.addJavaDocLine("/**");
//      sb.append(" * ");
//      sb.append(introspectedTable.getFullyQualifiedTable());
//      innerClass.addJavaDocLine(sb.toString());
//
//      sb.setLength(0);
//      sb.append(" * @author ");
//      sb.append(systemPro.getProperty("user.name"));
//      sb.append(" ");
//      sb.append(currentDateStr);
//
//      //      addJavadocTag(innerClass, markAsDoNotDelete);
//
//      innerClass.addJavaDocLine(" */");
    }
}


MyToStringPlugin

package com.hg.util;

import java.util.Iterator;
import java.util.List;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.PluginAdapter;
import org.mybatis.generator.api.dom.java.Field;
import org.mybatis.generator.api.dom.java.FullyQualifiedJavaType;
import org.mybatis.generator.api.dom.java.JavaVisibility;
import org.mybatis.generator.api.dom.java.Method;
import org.mybatis.generator.api.dom.java.TopLevelClass;

/**
 * mybatis generator 自定义toString插件
 * 基于MBG 1.3.2
 */
public class MyToStringPlugin extends PluginAdapter {
    public MyToStringPlugin() {
    }

    public boolean validate(List<String> warnings) {
        return true;
    }

    public boolean modelBaseRecordClassGenerated(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
        this.generateToString(introspectedTable, topLevelClass);
        return true;
    }

    public boolean modelRecordWithBLOBsClassGenerated(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
        this.generateToString(introspectedTable, topLevelClass);
        return true;
    }

    public boolean modelPrimaryKeyClassGenerated(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
        this.generateToString(introspectedTable, topLevelClass);
        return true;
    }

    private void generateToString(IntrospectedTable introspectedTable, TopLevelClass topLevelClass) {
        Method method = new Method();
        method.setVisibility(JavaVisibility.PUBLIC);
        method.setReturnType(FullyQualifiedJavaType.getStringInstance());
        method.setName("toString");
        if (introspectedTable.isJava5Targeted()) {
            method.addAnnotation("@Override");
        }
        
        //添加方法注释
        this.context.getCommentGenerator().addGeneralMethodComment(method, introspectedTable);

        //下面两句method.addBodyLine使用其中之一即可
        
        //使用自定义toString工具类
        //method.addBodyLine("return ToStringUtils.toSimpleString(this);");
        
        //使用commons-lang3的工具类
        //添加包
        topLevelClass.addImportedType("org.apache.commons.lang3.builder.ToStringBuilder");
        topLevelClass.addImportedType("org.apache.commons.lang3.builder.ToStringStyle");
        method.addBodyLine("return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE);");

        //添加方法
        topLevelClass.addMethod(method);
    }    /*
    private void generateToString(IntrospectedTable introspectedTable, TopLevelClass topLevelClass) {
        Method method = new Method();
        method.setVisibility(JavaVisibility.PUBLIC);
        method.setReturnType(FullyQualifiedJavaType.getStringInstance());
        method.setName("toString");
        if (introspectedTable.isJava5Targeted()) {
            method.addAnnotation("@Override");
        }

        this.context.getCommentGenerator().addGeneralMethodComment(method, introspectedTable);
        method.addBodyLine("StringBuilder sb = new StringBuilder();");
        method.addBodyLine("sb.append(getClass().getSimpleName());");
        method.addBodyLine("sb.append(\" [\");");
        StringBuilder sb = new StringBuilder();
        Iterator i$ = topLevelClass.getFields().iterator();

        while(i$.hasNext()) {
            Field field = (Field)i$.next();
            String property = field.getName();
            sb.setLength(0);
            sb.append("sb.append(\"").append(", ").append(property).append("=\")").append(".append(").append(property).append(");");
            method.addBodyLine(sb.toString());
        }

        method.addBodyLine("sb.append(\"]\");");
        method.addBodyLine("return sb.toString();");
        topLevelClass.addMethod(method);
    }
    */
}