Use Mybatis generator to automatically generate code, Oracle database only

1. Use Mybatis generator to automatically generate code, only for Oracle database

Use Mybatis generator to automatically generate code, Oracle database only

1. Introduce the required dependencies and plug-ins into the pom.xml file

<dependency>
    <groupId>org.mybatis.generator</groupId>
    <artifactId>mybatis-generator-core</artifactId>
    <version>1.3.2</version>
</dependency>

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

2. Create generator.xml in the resource directory, as follows
Insert image description here

<?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>

    <!-- 指定数据连接驱动jar地址,这个是我的地址,需要你换成自己的  网上很多自己下-->
    <classPathEntry location="G:\maven-package\repository\oracle\ojdbc\1.0.0\ojdbc-1.0.0.jar"/>

    <!-- 一个数据库一个context -->
    <context id="infoGuardian">

	<!-- 不需要改-->
        <commentGenerator>
            <property name="suppressDate" value="true"/>
            <property name="suppressAllComments" value="true" />
        </commentGenerator>

        <!-- jdbc连接 填写数据库的信息-->
        <jdbcConnection driverClass="oracle.jdbc.driver.OracleDriver"
                        connectionURL="xxx.xxx.xxx"
                        userId="xxx"
                        password="xxx" >
            <property name="nullCatalogMeansCurrent" value="true" />
        </jdbcConnection>

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

        <!-- 生成实体类地址 targetPackage需要替换成你自己的 -->
        <javaModelGenerator targetPackage="xxx.xxx.xxx"
                            targetProject="src/main/java">
            <property name="enableSubPackages" value="true"/>
            <property name="trimStrings" value="true"/>
        </javaModelGenerator>

        <!-- 生成mapxml文件 targetPackage需要替换成你自己的-->
        <sqlMapGenerator targetPackage="xxx.xxx.xxx">
            <property name="enableSubPackages" value="true"/>
        </sqlMapGenerator>

        <!-- 生成mapxml对应client,也就是接口dao  targetPackage需要替换成你自己的 -->
        <javaClientGenerator type="XMLMAPPER"
                             targetPackage="xxx.xxx.xxx"
                              targetProject="src/main/java">
            <property name="enableSubPackages" value="true"/>
        </javaClientGenerator>
        
        <!-- 一个表一个table,多个table再创建一个<table></table>标签即可
        schema:指定数据库名
        tableName:指定表名
        domainObjectName:指定生成的类名,与tableName保持一致即可
        -->
        <table
                schema="xxx"
                tableName="xxx"
                domainObjectName="xxx"
                enableCountByExample="false"
                enableDeleteByExample="false"
                enableSelectByExample="false"
                enableUpdateByExample="false">
        </table>

    </context>

</generatorConfiguration>


3. Execute in IDEA, double-click mybatis-generator:generate, if not found, refresh the plug-in
Insert image description here

2. Mybatis generator generates custom comments for entity classes

Mybatis generator generates custom comments for entity classes (read comments from database fields and add them to entity classes without modifying the source code)

We all know that the comments automatically generated by mybatis generator have no practical effect and also increase the amount of code. If comments can be retrieved from the database, it will not only greatly increase the readability of the code, but also reduce the workload of manually adding comments later.

1. First define the annotation generation plug-in

MyCommentGenerator.java

package com.ilovey.mybatis.comment;


import org.mybatis.generator.api.IntrospectedColumn;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.dom.java.Field;
import org.mybatis.generator.api.dom.java.InnerClass;
import org.mybatis.generator.api.dom.java.Method;
import org.mybatis.generator.internal.DefaultCommentGenerator;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;

/**
 * mybatis generator生成注释插件
 * <p>
 * Created by huhaichao on 2017/5/15.
 */
public class MyCommentGenerator extends DefaultCommentGenerator {
    
    
    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 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().replace("\n", " "));
        field.addJavaDocLine(" */");
    }

    public void addFieldComment(Field field, IntrospectedTable introspectedTable) {
    
    

    }

    public void addGeneralMethodComment(Method method, IntrospectedTable introspectedTable) {
    
    

    }

    public void addGetterComment(Method method, IntrospectedTable introspectedTable,
                                 IntrospectedColumn introspectedColumn) {
    
    

    }

    public void addSetterComment(Method method, IntrospectedTable introspectedTable,
                                 IntrospectedColumn introspectedColumn) {
    
    

    }

    public void addClassComment(InnerClass innerClass, IntrospectedTable introspectedTable, boolean markAsDoNotDelete) {
    
    

    }

    public void addClassComment(InnerClass innerClass, IntrospectedTable introspectedTable) {
    
    
    }


}

2. Then configure the plug-in for mybatisgenerator

<?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>
    <context id="context1">
        <plugin type="org.mybatis.generator.plugins.SerializablePlugin"/>
    
        <!-- 使用自定义的插件 -->
        <commentGenerator type="com.ilovey.mybatis.comment.MyCommentGenerator">

        </commentGenerator>


        <jdbcConnection driverClass="com.mysql.jdbc.Driver"
         connectionURL="jdbc:mysql://localhost:3306/test?useUnicode=true&amp;characterEncoding=UTF8"
         userId="root" password="123456">
        </jdbcConnection>
        
        <javaModelGenerator targetPackage="com.ilovey.biz.entity.base"
         targetProject="ilovey.biz/src/main/java"/>
        <sqlMapGenerator targetPackage="com.ilovey.biz.mapper.base"
         targetProject="ilovey.biz/src/main/resources"/>
        <javaClientGenerator targetPackage="com.ilovey.biz.mapper.base"
         targetProject="ilovey.biz/src/main/java" type="XMLMAPPER"/>
        
        <table tableName="us_user_info"  domainObjectName="UsUserInfo">
            <generatedKey column="id" sqlStatement="MySql" identity="true"/>
        </table>


    </context>
</generatorConfiguration>

3. Use mybatis generator to automatically generate code

Since we are using a maven project and a custom plug-in, we use the main method to start it, which is more applicable to the scenario and can generate the code into the corresponding project directory, eliminating the need for copying (of course you can also use maven Plug-in, console, eclipse plug-in and other ways to start).

Note: The project where the current class is located needs to add the dependency package of mybatis generator.

The startup class is as follows

package com.ilovey.mybatis;

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.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * 运行此方法生成mybatis代码
 * 生成代码自动放入对应目录
 * 配置文件targetProject应从项目名称开始到要生成到的classpath
 * Created by huhaichao on 2017/5/15.
 */
public class MyBatisGeneratorRun {
    
    

    public static void main(String[] args) throws Exception{
    
    
        MyBatisGeneratorRun app = new MyBatisGeneratorRun();

        System.out.println(app.getClass().getResource("/").getPath());
        app.generator();
        System.out.println(System.getProperty("user.dir"));
    }

    public void generator() throws Exception{
    
    

        List<String> warnings = new ArrayList<String>();
        boolean overwrite = true;
        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("generatorConfig.xml");
        ConfigurationParser cp = new ConfigurationParser(warnings);
        Configuration config = cp.parseConfiguration(resourceAsStream);
        DefaultShellCallback callback = new DefaultShellCallback(overwrite);
        MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
        myBatisGenerator.generate(null);

        for(String warning:warnings){
    
    
            System.out.println(warning);
        }
    }
}

Then paste the maven dependencies of the project. You can take a look if you need it.

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>party.lovey</groupId>
    <artifactId>generator</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <dependencies>
        <dependency>
            <groupId>org.mybatis.generator</groupId>
            <artifactId>mybatis-generator-core</artifactId>
            <version>1.3.6</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.29</version>
        </dependency>
    </dependencies>
    
</project>

4. Generate effects

package com.ilovey.biz.entity.base;

import java.io.Serializable;
import java.util.Date;

public class UsUserInfo implements Serializable {
    
    
    /**
     * 
     */
    private Integer id;

    /**
     * 用户id
     */
    private Integer userId;

    /**
     * 昵称
     */
    private String nickName;

    /**
     * 头像
     */
    private String headImage;

    /**
     * 手机号码
     */
    private String mobile;

    /**
     * 性别(0保密,1男,2女)
     */
    private Integer sex;

    /**
     * 地区
     */
    private Integer region;

    /**
     * 个性签名
     */
    private String signature;

    /**
     * 创建时间
     */
    private Date createTime;

    /**
     * 更新时间
     */
    private Date updateTime;

    //setter 和 getter方法省略
}

Guess you like

Origin blog.csdn.net/qq_41787812/article/details/133244613