MyBatis Generator简介

业务需求不断变更,数据库表结构不断修改,是我们逃不出的宿命。工欲善其事,必先利其器,是时候祭出神器了:MyBatis Generator(简称:MBG),它是一个用于所有版本MyBatis的代码自动生成器。它可以根据数据库的表自动为项目生产对应的实体类、Mapper、DAO,包括简单CRUD数据库操作(创建、查询、更新、删除)。解放了我们的双手,不必做重复性的机械工作。节省下不少时间,不用再苦哈哈的加班了,还可以和妹纸去约会。(前提是你得先有个妹纸🤐)

创建一个MySQL表

为了方便演示创建一个MySQL表,表结构比较简单,是一个用户信息表:

CREATE TABLE `user_info` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) DEFAULT NULL,
  `age` int(11) DEFAULT NULL,
  `create_time` datetime DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

创建一个SpringBoot项目

以使用IntelliJ IDEA为例,创建一个SpringBoot项目。点击File->New->Projects…,选择Spring Initializr,如下图:

springboot实现订单编号生成 springboot编码_java


点击Next,输入GroupArtifact等信息,如下图:

springboot实现订单编号生成 springboot编码_springboot_02


点击Next,选择Web,并勾选Spring Web,如下图:

springboot实现订单编号生成 springboot编码_springboot_03


点击Next,输入Project nameProject location等信息,如下图:

springboot实现订单编号生成 springboot编码_java_04


最后,点击Finish,一个SpringBoot项目就创建完了。

引入MyBatis Generator的Maven插件

在pom.xml的plugins节点中添加如下内容:

<plugin>
    <groupId>org.mybatis.generator</groupId>
    <artifactId>mybatis-generator-maven-plugin</artifactId>
    <version>1.4.0</version>
    <configuration>
        <overwrite>true</overwrite>
    </configuration>
    <dependencies>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>${mysql.version}</version>
        </dependency>
    </dependencies>
</plugin>

配置MyBatis Generator的Maven插件

在resources文件夹中创建一个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="application.properties"></properties>
    <!--defaultModelType用于指定生成对象的样式,flat表示每一张表只生成一个实体类,这个实体类包含表中的所有字段。-->
    <context id="MySQLTables" targetRuntime="MyBatis3" defaultModelType="flat">
        <property name="javaFileEncoding" value="UTF-8"/>

        <!-- 生成的实体类实现序列化接口 -->
        <plugin type="org.mybatis.generator.plugins.SerializablePlugin"/>

        <commentGenerator>
            <property name="dateFormat" value="yyyy-MM-dd HH:mm:ss"/>
        </commentGenerator>

        <!--数据库连接信息-->
        <jdbcConnection driverClass="${spring.datasource.driverClassName}"
                        connectionURL="${spring.datasource.url}"
                        userId="${spring.datasource.username}"
                        password="${spring.datasource.password}">
        </jdbcConnection>

        <!-- 配置生成的实体类位置 -->
        <javaModelGenerator targetPackage="one.more.mybatisgenerator.model" targetProject="src/main/java">
            <!-- 设置是否在setter方法中,对String类型字段调用trim()方法 -->
            <property name="trimStrings" value="true"/>
        </javaModelGenerator>

        <!-- 配置接口位置 -->
        <!-- type设置为ANNOTATEDMAPPER,基于注解的Mapper,不会有对应的xml文件生成-->
        <javaClientGenerator targetPackage="one.more.mybatisgenerator.mapper" targetProject="src/main/java"
                             type="ANNOTATEDMAPPER">
        </javaClientGenerator>

        <!-- 配置数据库表 -->
        <table tableName="user_info">
            <!--在生成的insert元素上添加useGeneratedKeys=”true”和keyProperty属性-->
            <generatedKey column="id" sqlStatement="JDBC"/>
        </table>
    </context>
</generatorConfiguration>

以上就是最基础简介的配置了,在实际的开发过程中就够用。如果有小伙伴还有需要更多的配置功能,可以官方网站(https://mybatis.org/generator/configreference/xmlconfig.html)查看。

自动生成代码

下面就是最激动人心的时刻了,一键自动生成代码。在Maven插件工具栏中,可以看到mybatis-generator插件,双击其中的generate选项即可,如下图:

springboot实现订单编号生成 springboot编码_mybatis_05


构建成功以后,就可以看到生成的代码了,如下图:

springboot实现订单编号生成 springboot编码_mybatis_06

验证自动生成的代码

验证之前还有一个步骤不要漏掉,就是在启动类上加上MapperScan注解,比如:

@SpringBootApplication
@MapperScan("one.more.mybatisgenerator.mapper")
public class MybatisGeneratorDemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(MybatisGeneratorDemoApplication.class, args);
    }

}
新增数据

随机生成一个UserInfo示例,插入到数据库中:

public UserInfo add() {
        Random random = new Random(System.currentTimeMillis());
        UserInfo userInfo = new UserInfo();
        userInfo.setName("name" + random.nextInt(100));
        userInfo.setAge(random.nextInt(100));
        userInfo.setCreateTime(new Date());
        
        int rows = userInfoMapper.insert(userInfo);
        System.out.println("rows:" + rows);
        return userInfo;
    }
查询数据

查询数据库里age大于某个值的user_info数据:

public List<UserInfo> getGreaterThan(Integer age) {
        UserInfoExample example = new UserInfoExample();
        Criteria criteria = example.createCriteria();
        criteria.andAgeGreaterThan(age);
        return userInfoMapper.selectByExample(example);
    }