MyBatis Generator的使用

使用MyBatis Generator(MBG)可以自动生成model层中的对象,并可根据数据库中的表字段,自动生成Getter和Setter,还可以自定义生成其他的方法,例如:toString()方法等。当数据库中有多张表时,使用MBG可以自动生成对象,免去编写大量重复的代码。

下面简单的记录MBG的使用:

设计数据库表

新建一个数据库mbg_test,使用Navicat设计两张数据库表:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
/*
Navicat MySQL Data Transfer

Source Server : root
Source Server Version : 50733
Source Host : localhost:3306
Source Database : mbg_test

Target Server Type : MYSQL
Target Server Version : 50733
File Encoding : 65001

Date: 2021-02-05 21:18:17
*/

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for product
-- ----------------------------
DROP TABLE IF EXISTS `product`;
CREATE TABLE `product` (
`id` int(11) NOT NULL,
`title` varchar(255) DEFAULT NULL,
`price` decimal(10,2) DEFAULT NULL,
`create_time` datetime DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
`update_time` datetime DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` int(11) NOT NULL,
`username` varchar(255) DEFAULT NULL,
`password` varchar(255) DEFAULT NULL,
`create_time` datetime DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
`update_time` datetime DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

新建Maven工程

  1. pom.xml中添加依赖:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    <dependencies>
    <dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
    <scope>test</scope>
    </dependency>
    <dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.4.1</version>
    </dependency>
    <dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.38</version>
    </dependency>
    <!-- MyBatis 生成器 -->
    <dependency>
    <groupId>org.mybatis.generator</groupId>
    <artifactId>mybatis-generator-core</artifactId>
    <version>1.3.3</version>
    </dependency>
    <dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-api</artifactId>
    <version>1.7.12</version>
    </dependency>
    <dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-log4j12</artifactId>
    <version>1.7.12</version>
    </dependency>
    <dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.17</version>
    </dependency>
    </dependencies>
  2. 搭建项目结构:
    yJUTfg.png

  3. 新建并编辑generatorConfig.xml文件:
    具体的标签配置可以参照《MyBatis从入门到精通》的 5.1 XML配置详解

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    <?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="MySqlContext" targetRuntime="MyBatis3" defaultModelType="flat">
    <property name="beginningDelimiter" value="`"/>
    <property name="endingDelimiter" value="`"/>
    <property name="javaFileEncoding" value="UTF-8"/>
    <!--可以自定义生成model的代码注释-->
    <commentGenerator type="com.mybatis.demo.mbg.CommentGenerator">
    <property name="suppressDate" value="true"/>
    <property name="addRemarkComments" value="true"/>
    </commentGenerator>
    <!--配置数据库连接-->
    <jdbcConnection driverClass="com.mysql.jdbc.Driver"
    connectionURL="jdbc:mysql://localhost:3306/mbg_test?useSSL=false"
    userId="root"
    password="123456">
    </jdbcConnection>
    <!--指定生成model的路径-->
    <javaModelGenerator targetPackage="com.mybatis.demo.mbg.model" targetProject="src/main/java">
    </javaModelGenerator>
    <!--指定生成mapper.xml的路径, windows中使用 "\", 类Unix使用 "/"-->
    <sqlMapGenerator targetPackage="com.mybatis.demo.mbg.mapper" targetProject="src/main/resources"/>
    <!--指定生成mapper接口的的路径-->
    <javaClientGenerator type="XMLMAPPER" targetPackage="com.mybatis.demo.mbg.mapper" targetProject="src/main/java"/>
    <!--生成全部表tableName设为%-->
    <table tableName="%">
    <generatedKey column="id" sqlStatement="MySql"/>
    </table>
    </context>
    </generatorConfiguration>
  4. 新建并编辑Generator.java文件:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    package com.mybatis.demo.mbg;

    /**
    * @author wangtao
    * @version 0.1 2021-02-05 21:50
    */
    import java.io.InputStream;
    import java.util.ArrayList;
    import java.util.List;

    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;

    public class Generator {
    public static void main(String[] args) throws Exception {
    //MBG 执行过程中的警告信息
    List<String> warnings = new ArrayList<String>();
    //当生成的代码重复时,覆盖原代码
    boolean overwrite = true;
    //读取我们的 MBG 配置文件
    InputStream is = Generator.class.getResourceAsStream("/generator/generatorConfig.xml");
    ConfigurationParser cp = new ConfigurationParser(warnings);
    Configuration config = cp.parseConfiguration(is);
    is.close();

    DefaultShellCallback callback = new DefaultShellCallback(overwrite);
    //创建 MBG
    MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
    //执行生成代码
    myBatisGenerator.generate(null);
    //输出警告信息
    for(String warning : warnings){
    System.out.println(warning);
    }
    }
    }
  5. 新建并编辑CommentGenerator.java文件,以生成文档注释:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    package com.mybatis.demo.mbg;

    import org.mybatis.generator.api.IntrospectedColumn;
    import org.mybatis.generator.api.IntrospectedTable;
    import org.mybatis.generator.api.dom.java.Field;
    import org.mybatis.generator.internal.DefaultCommentGenerator;
    import org.mybatis.generator.internal.util.StringUtility;

    import java.util.Properties;

    /**
    * 自定义注释生成器
    * Created by macro on 2018/4/26.
    */
    public class CommentGenerator extends DefaultCommentGenerator {
    private boolean addRemarkComments = false;

    /**
    * 设置用户配置的参数
    */
    @Override
    public void addConfigurationProperties(Properties properties) {
    super.addConfigurationProperties(properties);
    this.addRemarkComments = StringUtility.isTrue(properties.getProperty("addRemarkComments"));
    }

    /**
    * 给字段添加注释
    */
    @Override
    public void addFieldComment(Field field, IntrospectedTable introspectedTable,
    IntrospectedColumn introspectedColumn) {
    String remarks = introspectedColumn.getRemarks();
    //根据参数和备注信息判断是否添加备注信息
    if (addRemarkComments && StringUtility.stringHasValue(remarks)) {
    addFieldJavaDoc(field, remarks);
    }
    }

    /**
    * 给model的字段添加注释
    */
    private void addFieldJavaDoc(Field field, String remarks) {
    //文档注释开始
    field.addJavaDocLine("/**");
    //获取数据库字段的备注信息
    String[] remarkLines = remarks.split(System.getProperty("line.separator"));
    for (String remarkLine : remarkLines) {
    field.addJavaDocLine(" * " + remarkLine);
    }
    addJavadocTag(field, false);
    field.addJavaDocLine(" */");
    }

    }
  6. 运行Generator.java,即可生成对应数据库表的model、Mapper接口、mapper.xml映射文件。

测试

创建并编辑UserMapperTest.java,用来测试接口:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package com.mybatis.demo.mbg.mapper;

/**
* @author wangtao
* @version 0.1 2021-02-05 22:35
*/

import java.io.IOException;
import java.io.Reader;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.BeforeClass;
import org.junit.Test;

import com.mybatis.demo.mbg.model.User;
public class UserMapperTest {
private static SqlSessionFactory sqlSessionFactory;

@BeforeClass
public static void init(){
try {
Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
reader.close();
} catch (IOException ignore) {
ignore.printStackTrace();
}
}

public SqlSession getSqlSession(){
return sqlSessionFactory.openSession();
}

@Test
public void testSelectByPrimaryKey(){
//获取 sqlSession
SqlSession sqlSession = getSqlSession();
try {
//获取 UserMapper 接口
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
//调用 selectByPrimaryKey 方法,查询 id = 1 的用户
User user = userMapper.selectByPrimaryKey(1);

System.out.println(user);
} finally {
//不要忘记关闭 sqlSession
sqlSession.close();
}
}
}

能查到数据库中的数据,表明MBG成功了