mybatis自动生成model、dao及对应的mapper.xml文件

背景:

  日常开发中,如果新建表,手动敲写model、dao和对应的mapper.xml文件,费时费力且容易出错,

所以采用mybatis自动生成model、dao及对应的mapper.xml文件。代码注释风格采用自定义注释。

环境:

  jdk1.8,maven,mysql

项目结构:

mybatis自动生成model、dao及对应的mapper.xml文件


 mbg-comment:自定义注释

pom文件:

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.lw</groupId>
    <artifactId>mbg-comment</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>mbg-comment</name>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <mybatis.generator.version>1.4.0</mybatis.generator.version>
    </properties>

    <dependencies>
        <dependency>
           <groupId>org.mybatis.generator</groupId>
           <artifactId>mybatis-generator-core</artifactId>
           <version>${mybatis.generator.version}</version>
       </dependency>
    </dependencies>

</project>

如果要实现自定义注释功能,需要实现CommentGenerator接口;

我采用的是,创建EmptyCommentGenerator抽象类实现CommentGenerator接口,创建MyCommentGenerator继承EmptyCommentGenerator抽象类;

mybatis自动生成model、dao及对应的mapper.xml文件

 EmptyCommentGenerator抽象类重写CommentGenerator接口中所有的方法即可;

 MyCommentGenerator类代码,将需要具体实现的方法重写逻辑即可;

mybatis自动生成model、dao及对应的mapper.xml文件
package com.lw.mbgcomment.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.TopLevelClass;

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

/**
 * @Classname MySQLCommentGenerator
 * @Description 自定义注释
 * @Date 2019/12/6 13:32
 * @Author lw
 */
public class MyCommentGenerator extends EmptyCommentGenerator {

    private Properties properties;

    public MyCommentGenerator() {
        properties = new Properties();
    }

    /**
     * 添加配置属性
     *
     * @param properties
     */
    @Override
    public void addConfigurationProperties(Properties properties) {
        this.properties.putAll(properties);
    }

    /**
     * 模型类注释
     *
     * @param topLevelClass
     * @param introspectedTable
     */
    @Override
    public void addModelClassComment(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
        String author = properties.getProperty("author");
        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(" */");
    }

    /**
     * 字段注释
     *
     * @param field
     * @param introspectedTable
     * @param introspectedColumn
     */
    @Override
    public void addFieldComment(Field field, IntrospectedTable introspectedTable, IntrospectedColumn introspectedColumn) {
        // 获取列注释
        String remarks = introspectedColumn.getRemarks();
        // 组装注释模板
        field.addJavaDocLine("/** " + remarks + " */");
    }

}
View Code

mbg-service:代码生成

pom文件:

mybatis自动生成model、dao及对应的mapper.xml文件
<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.lw</groupId>
    <artifactId>mbg-service</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>mbg-service</name>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.encoding>UTF-8</maven.compiler.encoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <mybatis.generator.version>1.4.0</mybatis.generator.version>
        <mysql.connector.version>5.1.40</mysql.connector.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.mybatis.generator</groupId>
            <artifactId>mybatis-generator-core</artifactId>
            <version>${mybatis.generator.version}</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>${mysql.connector.version}</version>
        </dependency>
       <!-- 通过java代码GeneratorClient运行main方法时,将此依赖放开;
            不然会找不到自定义注释类,要求classpath保持一致;-->
       <dependency>
            <groupId>com.lw</groupId>
            <artifactId>mbg-comment</artifactId>
            <version>0.0.1-SNAPSHOT</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.mybatis.generator</groupId>
                <artifactId>mybatis-generator-maven-plugin</artifactId>
                <version>${mybatis.generator.version}</version>
                <dependencies>
                    <dependency>
                    <groupId>mysql</groupId>
                    <artifactId>mysql-connector-java</artifactId>
                    <version>${mysql.connector.version}</version>
                </dependency>
                    <dependency>
                        <groupId>com.lw</groupId>
                        <artifactId>mbg-comment</artifactId>
                        <version>0.0.1-SNAPSHOT</version>
                    </dependency>
                </dependencies>
                <executions>
                    <execution>
                        <id>Generate MyBatis Artifacts</id>
                        <phase>package</phase>
                        <goals>
                            <goal>generate</goal>
                        </goals>
                    </execution>
                </executions>
                <configuration>
                    <!--允许移动生成的文件 -->
                    <verbose>true</verbose>
                    <!-- 是否覆盖 -->
                    <overwrite>true</overwrite>
                    <!-- 自动生成的配置文件 -->
                    <configurationFile>src/main/resources/generatorConfig.xml</configurationFile>
                </configuration>
            </plugin>
        </plugins>

        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>*.properties</include>
                    <include>*.xml</include>
                </includes>
                <excludes>
                    <exclude>generatorConfig-template.xml</exclude>
                </excludes>
                <filtering>false</filtering>
            </resource>
        </resources>
    </build>

</project>
View Code

生成代码配置文件:

mybatis自动生成model、dao及对应的mapper.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="jdbc.properties"/>

    <!-- 环境信息 -->
    <context id="myMbg" targetRuntime="MyBatis3Simple" defaultModelType="flat">
        <!-- 生成的Java文件的编码 -->
        <property name="javaFileEncoding" value="UTF-8"/>
        <!-- 格式化java代码 -->
        <property name="javaFormatter" value="org.mybatis.generator.api.dom.DefaultJavaFormatter"/>
        <!-- 格式化XML代码 -->
        <property name="xmlFormatter" value="org.mybatis.generator.api.dom.DefaultXmlFormatter"/>
        <!-- 标记数据库对象名的符号,MYSQL默认是`反引号 -->
        <property name="beginningDelimiter" value="`"/>
        <property name="endingDelimiter" value="`"/>

        <!-- 自定义注释生成器 -->
        <commentGenerator type="com.lw.mbgcomment.comment.MyCommentGenerator">
            <property name="author" value="lw"/>
            <property name="dateFormat" value="yyyy/MM/dd HH:mm:ss"/>
        </commentGenerator>

        <!-- jdbc配置 -->
        <jdbcConnection driverClass="${jdbc_driver}" connectionURL="${jdbc_url}" userId="${jdbc_username}" password="${jdbc_password}">
            <property name="useInformationSchema" value="true" />
        </jdbcConnection>

        <!-- java类型处理 -->
        <javaTypeResolver>
            <property name="forceBigDecimals" value="false"/>
        </javaTypeResolver>

        <!-- 生成Entity类存放位置 -->
        <!-- 注意:通过java代码GeneratorClient运行main方法时,targetProject="mbg-service/src/main/java" -->
        <javaModelGenerator targetPackage="com.lw.mbgservice.entity" targetProject="src/main/java">
            <!-- 是否允许建立子包(对应MySql的scheme),默认为false -->
            <property name="enableSubPackages" value="true"/>
            <!-- 设置是否在getter方法中,对String类型字段调用trim()方法 -->
            <property name="trimStrings" value="false"/>
        </javaModelGenerator>

        <!-- 生成映射文件存放位置 -->
        <!-- 注意:通过java代码GeneratorClient运行main方法时,targetProject="mbg-service/src/main/java" -->
        <sqlMapGenerator targetPackage="mapping" targetProject="src/main/resources">
            <property name="enableSubPackages" value="true"/>
        </sqlMapGenerator>

        <!-- 生成Dao类存放位置 -->
        <!-- 注意:通过java代码GeneratorClient运行main方法时,targetProject="mbg-service/src/main/java" -->
        <javaClientGenerator type="XMLMAPPER" targetPackage="com.lw.mbgservice.dao" targetProject="src/main/java">
            <property name="enableSubPackages" value="true"/>
        </javaClientGenerator>

        <!-- 设置数据库的表名和实体类名 -->
        <table tableName="c_bankcard_agreement" domainObjectName="BankcardAgreementEntity"/>
        <table tableName="b_phone_white_pro" domainObjectName="PhoneWhitePro"/>
    </context>

</generatorConfiguration>
View Code

注意:注释type是自定义注释类

mybatis自动生成model、dao及对应的mapper.xml文件


 代码生成方式,本文讲述两种(java代码运行和mvn插件):

1.mvn插件

打开maven窗口,mbg-service服务Plugins目录,双击mybatis-generator:generate即可

mybatis自动生成model、dao及对应的mapper.xml文件

 2.java代码运行

mybatis自动生成model、dao及对应的mapper.xml文件
package com.lw.mbgservice.client;

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;

/**
 * @Classname GeneratorClient
 * @Description 代码生成客户端
 * @Date 2019/12/12 9:03
 * @Author lw
 */
public class GeneratorClient {

    /**
     * 代码生成:
     *  1.将pom.xml中,自定义注释mbg-comment依赖放开
     *  2.generatorConfig.xml文中,targetProject属性加上项目名称,使用targetProject="mbg-service/src/main/java"
     *
     * @param args
     */
    public static void main(String[] args) {
        List<String> warnings = new ArrayList<>();
        boolean overwrite = true;

        try{
            ClassLoader classloader = Thread.currentThread().getContextClassLoader();
            InputStream is = classloader.getResourceAsStream("generatorConfig.xml");
            ConfigurationParser cp = new ConfigurationParser(warnings);
            Configuration config = cp.parseConfiguration(is);
            DefaultShellCallback callback = new DefaultShellCallback(overwrite);
            MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
            myBatisGenerator.generate(null);
        }catch (Exception e){
            e.printStackTrace();
        }

        warnings.forEach(warning -> {
            System.out.println("=== " + warning);
        });
    }

}
View Code

生成代码效果

mybatis自动生成model、dao及对应的mapper.xml文件


遇到的问题

1.中文乱码

在generatorConfig.xml中,添加  <property name="javaFileEncoding" value="UTF-8"/> 

mybatis自动生成model、dao及对应的mapper.xml文件

 2.数据库字段注释中文乱码,在数据库连接url中添加 characterEncoding=utf-8 

mybatis自动生成model、dao及对应的mapper.xml文件

 数据库字符集设置:

mybatis自动生成model、dao及对应的mapper.xml文件

 3.找不到自定义注释类 com.lw.mbgcomment.comment.MyCommentGenerator 

需要保证classpath一致,在pom文件<build/>中引入mbg-comment依赖

mybatis自动生成model、dao及对应的mapper.xml文件

mybatis自动生成model、dao及对应的mapper.xml文件

上一篇:入门移动端混合开发 实战京东 APP(完整更新)


下一篇:[UIApplication sharedApplication].keyWindow和[[UIApplication sharedApplication].delegate window]区别