mybatis-generator逆向工程詳解大全

1.建maven工程(傻子都會)如下圖:

在這裏插入圖片描述

2.pom文件內容:jar包就這幾個

在這裏插入圖片描述

3.兩 個類分別如下:

MyCommentGenerator.java和RunClass.java(隨你放哪個位置)

**第一個類*******************************************************

/**
 *    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 mybatis_generator.mybatis_generator;
 
import static org.mybatis.generator.internal.util.StringUtility.isTrue;
 
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.Properties;
 
import org.mybatis.generator.api.CommentGenerator;
import org.mybatis.generator.api.IntrospectedColumn;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.dom.java.CompilationUnit;
import org.mybatis.generator.api.dom.java.Field;
import org.mybatis.generator.api.dom.java.InnerClass;
import org.mybatis.generator.api.dom.java.InnerEnum;
import org.mybatis.generator.api.dom.java.JavaElement;
import org.mybatis.generator.api.dom.java.Method;
import org.mybatis.generator.api.dom.java.TopLevelClass;
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;
 
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;
 
    public MyCommentGenerator() {
        super();
        properties = new Properties();
        suppressDate = false;
        suppressAllComments = false;
        addRemarkComments = false;
    }
 
    public void addJavaFileComment(CompilationUnit compilationUnit) {
    }
 
    /**
     * 實體類對應的mapper.xml註釋,mapper類不加註釋,如有需要參考 DefaultCommentGenerator
     */
    public void addComment(XmlElement xmlElement) {
        if (suppressAllComments) {
            return;
        }
    }
 
    public void addRootComment(XmlElement rootElement) {
    	
    }
 
    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));
 
        addRemarkComments = isTrue(properties
                .getProperty(PropertyRegistry.COMMENT_GENERATOR_ADD_REMARK_COMMENTS));
        
        String dateFormatString = properties.getProperty(PropertyRegistry.COMMENT_GENERATOR_DATE_FORMAT);
        if (StringUtility.stringHasValue(dateFormatString)) {
            dateFormat = new SimpleDateFormat(dateFormatString);
        }
    }
 
    protected void addJavadocTag(JavaElement javaElement,
            boolean markAsDoNotDelete) {
        javaElement.addJavaDocLine(" *"); //$NON-NLS-1$
        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$
        }
        String s = getDateString();
        if (s != null) {
            sb.append(' ');
            sb.append(s);
        }
        javaElement.addJavaDocLine(sb.toString());
    }
 
    protected String getDateString() {
        if (suppressDate) {
            return null;
        } else if (dateFormat != null) {
            return dateFormat.format(new Date());
        } else {
            return new Date().toString();
        }
    }
 
    public void addClassComment(InnerClass innerClass,
            IntrospectedTable introspectedTable) {
        if (suppressAllComments) {
            return;
        }
        
        StringBuilder sb = new StringBuilder();
 
        innerClass.addJavaDocLine("/**"); //$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$
    }
 
//    public void addModelClassComment(TopLevelClass topLevelClass,
//            IntrospectedTable introspectedTable) {
//        if (suppressAllComments  || !addRemarkComments) {
//            return;
//        }
// 
//        StringBuilder sb = new StringBuilder();
// 
//        topLevelClass.addJavaDocLine("/**"); //$NON-NLS-1$
// 
//        String remarks = introspectedTable.getRemarks();
//        if (addRemarkComments && StringUtility.stringHasValue(remarks)) {
//            topLevelClass.addJavaDocLine(" * Database Table Remarks:");
//            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(introspectedTable.getFullyQualifiedTable());
//        topLevelClass.addJavaDocLine(sb.toString());
// 
//        addJavadocTag(topLevelClass, true);
// 
//        topLevelClass.addJavaDocLine(" */"); //$NON-NLS-1$
//    }
    @Override
    public void addModelClassComment(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
        String author = "wmd";
//        String dateFormat = properties.getProperty("dateFormat", "yyyy-MM-dd");
//        SimpleDateFormat dateFormatter = new SimpleDateFormat(dateFormat);

        // 獲取表註釋
        String remarks = introspectedTable.getRemarks();

        topLevelClass.addJavaDocLine("/**");
        topLevelClass.addJavaDocLine(" * " + remarks);
        topLevelClass.addJavaDocLine(" *");
        topLevelClass.addJavaDocLine(" * @author " + author);
//        topLevelClass.addJavaDocLine(" * @date " + dateFormatter.format(new Date()));
        topLevelClass.addJavaDocLine(" */");
    }
 
    public void addEnumComment(InnerEnum innerEnum,
            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$
    }
 
    /**
     * 實體類字段註釋
     */
    public void addFieldComment(Field field,
            IntrospectedTable introspectedTable,
            IntrospectedColumn introspectedColumn) {
    	if (suppressAllComments) {
            return;
        }
 
        field.addJavaDocLine("/**"); //$NON-NLS-1$
 
        // 核心代碼 introspectedColumn.getRemarks() 就是獲取字段註釋
        StringBuilder sb = new StringBuilder();
        sb.append(" * " + introspectedColumn.getRemarks());
        sb.append("\n\t * [email protected]");
        sb.append("\n\t * " + LocalDateTime.now());
        field.addJavaDocLine(sb.toString());
        field.addJavaDocLine(" */"); 
    }
//    @Override
//    public void addFieldComment(Field field, IntrospectedTable introspectedTable, IntrospectedColumn introspectedColumn) {
//        // 獲取列註釋
//        String remarks = introspectedColumn.getRemarks();
//        field.addJavaDocLine("/**");
//        field.addJavaDocLine(" * " + remarks);
//        field.addJavaDocLine(" */");
//    }
 
    /**
     * 實體類的靜態字段
     */
    public void addFieldComment(Field field, IntrospectedTable introspectedTable) {
        if (suppressAllComments) {
            return;
        }
 
        StringBuilder sb = new StringBuilder();
 
        field.addJavaDocLine("/**"); 
        sb.append(" * [email protected]");
        sb.append("\n\t * " + LocalDateTime.now());
        field.addJavaDocLine(sb.toString());
        field.addJavaDocLine(" */");
    }
 
    /**
     * 實體類toString方法
     */
    public void addGeneralMethodComment(Method method,
            IntrospectedTable introspectedTable) {
        if (suppressAllComments) {
            return;
        }
 
       /* StringBuilder sb = new StringBuilder();
        method.addJavaDocLine("/**"); //$NON-NLS-1$
        method.addJavaDocLine(" * toString."); //$NON-NLS-1$
        sb.append(introspectedTable.getFullyQualifiedTable());
        method.addJavaDocLine(sb.toString());
        addJavadocTag(method, false);*/
        //method.addJavaDocLine(" */");
    }
    
    /**
     * 實體類getter方法註釋
     */
    public void addGetterComment(Method method,
            IntrospectedTable introspectedTable,
            IntrospectedColumn introspectedColumn) {
        if (suppressAllComments) {
            return;
        }
 
        StringBuilder sb = new StringBuilder();
 
        method.addJavaDocLine("/**"); //$NON-NLS-1$
        sb.append(" * " + introspectedColumn.getRemarks());
        method.addJavaDocLine(sb.toString());
        method.addJavaDocLine(" */"); //$NON-NLS-1$
    }
 
    /**
     * 實體類setter註釋
     */
    public void addSetterComment(Method method,
            IntrospectedTable introspectedTable,
            IntrospectedColumn introspectedColumn) {
        if (suppressAllComments) {
            return;
        }
 
        StringBuilder sb = new StringBuilder();
 
        method.addJavaDocLine("/**"); //$NON-NLS-1$
        sb.append(" * " + introspectedColumn.getRemarks());
        method.addJavaDocLine(sb.toString());
        method.addJavaDocLine(" */"); //$NON-NLS-1$
    }
 
    public void addClassComment(InnerClass innerClass,
            IntrospectedTable introspectedTable, boolean markAsDoNotDelete) {
        if (suppressAllComments) {
            return;
        }
 
        StringBuilder sb = new StringBuilder();
 
        innerClass.addJavaDocLine("/**"); //$NON-NLS-1$
        innerClass
                .addJavaDocLine(" * This class was generated by MyBatis Generator."); //$NON-NLS-1$
 
        sb.append(introspectedTable.getFullyQualifiedTable());
        innerClass.addJavaDocLine(sb.toString());
 
        addJavadocTag(innerClass, markAsDoNotDelete);
 
        innerClass.addJavaDocLine(" */"); //$NON-NLS-1$
    }
}```

**第二個類*****************************************************

package mybatis_generator.mybatis_generator;


import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.config.Configuration;
import org.mybatis.generator.config.xml.ConfigurationParser;
import org.mybatis.generator.internal.DefaultShellCallback;
 
import java.io.File;
import java.util.ArrayList;
import java.util.List;
 
public class RunClass {
    public static void main(String[] args) {
        try {
            List<String> warnings = new ArrayList<String>();
            boolean overwrite = true;
            File configFile = new File("src/main/resources/generatorConfig.xml");
            ConfigurationParser cp = new ConfigurationParser(warnings);
            Configuration config = cp.parseConfiguration(configFile);
            DefaultShellCallback callback = new DefaultShellCallback(overwrite);
            MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
            myBatisGenerator.generate(null);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

4.項目結構

在這裏插入圖片描述

5.最後只要運行runclass就可以得到實體、dao層、mapper文件,具體的生成方式都在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>
    <!-- 指定數據庫驅動包 -->
    <!-- <classPathEntry location="~\mysql\mysql-connector-java\5.1.46\mysql-connector-java-5.1.46.jar" /> -->
    <context id="MySQLTables" targetRuntime="MyBatis3">
    	<!-- 配置生成pojo的序列化的插件  -->
        <plugin type="org.mybatis.generator.plugins.SerializablePlugin" />
        
        <!-- 配置生成pojo的toString()方法的插件 -->
        <plugin type="org.mybatis.generator.plugins.ToStringPlugin" />
        
        <!-- 取消生成的註釋 -->
        <!-- <commentGenerator>
            <property name="suppressDate" value="false"/>
            <property name="suppressAllComments" value="false"/>
        </commentGenerator> -->
        <!-- 通過type指定自定義的註釋 -->
        <commentGenerator type="mybatis_generator.mybatis_generator.MyCommentGenerator">
	        <!-- 不要開啓,否則將不會使用自定義註釋 -->
	        <!-- <property name="suppressAllComments" value="true"> -->
        </commentGenerator>
  
 
        <!-- 數據庫連接參數 -->
        <jdbcConnection driverClass="com.mysql.jdbc.Driver"
                        connectionURL="jdbc:mysql://localhost:3306/ssm"
                        userId="root"
                        password="123456">
        </jdbcConnection>
 
        <javaTypeResolver>
            <property name="forceBigDecimals" value="false"/>
        </javaTypeResolver>
 
        <!-- 指定實體類 -->
        <javaModelGenerator targetPackage="com.wmd.entity"
                            targetProject=".\src\main\java">
            <property name="enableSubPackages" value="true"/>
            <property name="trimStrings" value="true"/>
        </javaModelGenerator>
 
        <!-- 創建SQL的Mapper文件 -->
        <sqlMapGenerator targetPackage="mapper"
                         targetProject=".\src\main\resources">
            <property name="enableSubPackages" value="true"/>
        </sqlMapGenerator>
 
        <!-- 指定Mapper文件XMLMAPPER生成xml ANNOTATEDMAPPER爲註解  -->
        <javaClientGenerator type="XMLMAPPER" targetPackage="com.wmd.dao"
                             targetProject=".\src\main\java">
            <property name="enableSubPackages" value="true"/>
        </javaClientGenerator>
 
        <!-- 指定數據庫哪些表生成代碼 -->
	    <table tableName="t_function" domainObjectName="function"
	    	enableCountByExample="false" enableDeleteByExample="false"
	    	enableUpdateByExample="false" enableSelectByExample="false">
	    </table>
    </context>
</generatorConfiguration>

6.只要跟着我的步驟無腦操作,最終就會將數據庫的錶轉換成實體、dao、mapper,而且實體字段的註釋和類註釋和getset註釋都是可以在MyCommentGenerator.java中自由編寫的,如下如: (萬一最後你還是沒有生成成功,不要着急,請把我的項目直接拿去,還是不行,我提頭來見!)

[項目代碼下載 mybatis-generator]:下載

補充:前提是數據庫已經有現成的表哦!!!!!!!

發佈了17 篇原創文章 · 獲贊 2 · 訪問量 2316
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章