易筋SpringBoot 2.1 | 第廿一篇:SpringBoot的Mybatis生成工具Generator

写作时间:2019-09-07
Spring Boot: 2.1 ,JDK: 1.8, IDE: IntelliJ IDEA

说明

让MyBatis更好用的工具: MyBatis Generator

MyBatis Generator (http://www.mybatis.org/generator/index.html)

  • MyBatis 代码生成器
  • 根据数据库生成相关代码
    • POJO
    • Mapper接口
    • SQL Map XML

运行MyBatis Generator

  1. 命令行
      java -jar mybatis-generator-core-x.x.x.jar -configfile \temp\generatorConfig.xml -overwrite

  1. Maven Plugin (mybatis-generator-maven-plugin)
    • mvn mybatis-generator:generate
    • ${basedir}/src/main/resources/generatorConfig.xml
  2. Eclipse Plugin
  3. Java 程序
  4. Ant Task

配置MyBatis Generator

generatorConfiguration
context

  • jdbcConnection
  • javaModelGenerator
  • sqlMapGenerator
  • javaClientGenerator (ANNOTATEDMAPPER / XMLMAPPER /MIXEDMAPPER)
  • table

生成时可以使用的插件

内置插件都在 org.mybatis.generator.plugins 包中

  • FluentBuilderMethodsPlugin
  • ToStringPlugin
  • SerializablePlugin
  • RowBoundsPlugin

使用生成的对象

  • 简单操作,直接使用生成的 xxxMapper 的方法
  • 复杂查询,使用生成的 xxxExample 对象

工程建立

参照教程【SpringBoot 2.1 | 第一篇:构建第一个SpringBoot工程】新建一个Spring Boot项目,名字叫demodbmybatisgenerator, 在目录src/main/java/resources 下找到配置文件application.properties,重命名为application.yml

在Dependency中选择
Developer Tools > Lombok
Web > Spring Web Starter
SQL > H2 DataBase / Mybatis Framework
Ops > Spring Boot Actuator。

在这里插入图片描述
pom.xml 修改spring-boot版本、mybatis的版本, 增加mybatis.generator, joda

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.1.7.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>
<dependencies>
	<dependency>
	    <groupId>org.mybatis.spring.boot</groupId>
	    <artifactId>mybatis-spring-boot-starter</artifactId>
	    <version>2.1.0</version>
	</dependency>
	<dependency>
	    <groupId>org.mybatis.generator</groupId>
	    <artifactId>mybatis-generator-core</artifactId>
	    <version>1.3.7</version>
	</dependency>
	<dependency>
	    <groupId>org.joda</groupId>
	    <artifactId>joda-money</artifactId>
	    <version>LATEST</version>
	</dependency>
</dependencies>

设置配置

src > main > resources > application.yml

mybatis:
  mapper-locations: 'classpath*:/mapper/**/*.xml'
  type-aliases-package: 'zgpeace.spring.mybatis.model'
  type-handlers-package: 'zgpeace.spring.mybatis.handler'
  configuration:
    map-underscore-to-camel-case: true

注释: mapper-locations 查找位置。

创建表sql

Resources.schema.sql

create table t_coffee (
    id bigint not null auto_increment,
    name varchar(255),
    price bigint not null,
    create_time timestamp,
    update_time timestamp,
    primary key (id)
);

Money类型转换类

zgpeace.spring.mybatis.handler.MoneyTypeHandler

package zgpeace.spring.mybatis.handler;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.joda.money.CurrencyUnit;
import org.joda.money.Money;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * exchange data type between Money and BigInt for 'CNY'
 */
public class MoneyTypeHandler extends BaseTypeHandler<Money> {
  @Override
  public void setNonNullParameter(PreparedStatement ps, int i, Money parameter, JdbcType jdbcType) throws SQLException {
    ps.setLong(i, parameter.getAmountMinorLong());
  }

  @Override
  public Money getNullableResult(ResultSet rs, String columnName) throws SQLException {
    return parseMoney(rs.getLong(columnName));
  }

  @Override
  public Money getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
    return parseMoney(rs.getLong(columnIndex));
  }

  @Override
  public Money getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
    return parseMoney(cs.getLong(columnIndex));
  }

  private Money parseMoney(Long value) {
    return Money.of(CurrencyUnit.of("CNY"), value / 100.0);
  }
}

Generator.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>
    <context id="H2Tables" targetRuntime="MyBatis3">
        <plugin type="org.mybatis.generator.plugins.FluentBuilderMethodsPlugin"/>
        <plugin type="org.mybatis.generator.plugins.ToStringPlugin"/>
        <plugin type="org.mybatis.generator.plugins.SerializablePlugin"/>
        <plugin type="org.mybatis.generator.plugins.RowBoundsPlugin"/>

        <jdbcConnection driverClass="org.h2.Driver"
                        connectionURL="jdbc:h2:mem:testdb"
                        userId="sa"
                        password="">
        </jdbcConnection>

        <javaModelGenerator targetPackage="zgpeace.spring.mybatis.model"
                            targetProject="./src/main/java">
            <property name="enableSubPackages" value="true"/>
            <property name="trimStrings" value="true"/>
        </javaModelGenerator>

        <sqlMapGenerator targetPackage="zgpeace.spring.mybatis.mapper"
                         targetProject="./src/main/resources/mapper">
            <property name="enableSubPackages" value="true"/>
        </sqlMapGenerator>

        <javaClientGenerator type="MIXEDMAPPER"
                             targetPackage="zgpeace.spring.mybatis.mapper"
                             targetProject="./src/main/java">
            <property name="enableSubPackages" value="true"/>
        </javaClientGenerator>

        <table tableName="t_coffee" domainObjectName="Coffee">
            <generatedKey column="id" sqlStatement="CALL IDENTITY()" identity="true"/>
            <columnOverride column="price" javaType="org.joda.money.Money" jdbcType="BIGINT"
                            typeHandler="zgpeace.spring.mybatis.handler.MoneyTypeHandler"/>
        </table>
    </context>
</generatorConfiguration>

注意:

  1. 这里配置的必须按照顺序优先级,否则出错。比如Plugin 一定在Connection之前,Connection一定在Generator之前.
  2. 手动创建里面的package:
    • zgpeace.spring.mybatis.mapper
    • zgpeace.spring.mybatis.model

Controller 用Generator生成代码

zgpeace.spring.mybatis.DemodbmybatisgeneratorApplication

package zgpeace.spring.mybatis;

import lombok.extern.slf4j.Slf4j;
import org.joda.money.CurrencyUnit;
import org.joda.money.Money;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@SpringBootApplication
@Slf4j
@MapperScan("zgpeace.spring.mybatis.mapper")
public class DemodbmybatisgeneratorApplication implements ApplicationRunner {
  public static void main(String[] args) {
    SpringApplication.run(DemodbmybatisgeneratorApplication.class, args);
  }

  @Override
  public void run(ApplicationArguments args) throws Exception {
    generateArtifacts();
  }
  
  private void generateArtifacts() throws Exception {
    List<String> warnings = new ArrayList<>();
    ConfigurationParser cp = new ConfigurationParser(warnings);
    Configuration config = cp.parseConfiguration(
        this.getClass().getResourceAsStream("/generatorConfig.xml")
    );
    DefaultShellCallback callback = new DefaultShellCallback(true);
    MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
    myBatisGenerator.generate(null);
  }
}

运行后生成了代码如图

注意: 运行后需要等一会,方能生成文件。耐心等待中…

CoffeeMapper
Coffee
CoffeeExample
CoffeeMapper.xml

在这里插入图片描述

Controller 验证表和数据可用

package zgpeace.spring.mybatis;

import lombok.extern.slf4j.Slf4j;
import org.joda.money.CurrencyUnit;
import org.joda.money.Money;
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 org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import zgpeace.spring.mybatis.mapper.CoffeeMapper;
import zgpeace.spring.mybatis.model.Coffee;
import zgpeace.spring.mybatis.model.CoffeeExample;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@SpringBootApplication
@Slf4j
@MapperScan("zgpeace.spring.mybatis.mapper")
public class DemodbmybatisgeneratorApplication implements ApplicationRunner {
  @Autowired
  private CoffeeMapper coffeeMapper;

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

  @Override
  public void run(ApplicationArguments args) throws Exception {
    playWithArtifacts();
  }

  private void playWithArtifacts() {
    Coffee espresso = new Coffee()
        .withName("espresso")
        .withPrice(Money.of(CurrencyUnit.of("CNY"), 20.0))
        .withCreateTime(new Date())
        .withUpdateTime(new Date());
    coffeeMapper.insert(espresso);

    Coffee latte = new Coffee()
        .withName("latte")
        .withPrice(Money.of(CurrencyUnit.of("CNY"), 30.0))
        .withCreateTime(new Date())
        .withUpdateTime(new Date());
    coffeeMapper.insert(latte);

    Coffee s = coffeeMapper.selectByPrimaryKey(1L);
    log.info("Coffee {}", s);

    CoffeeExample example = new CoffeeExample();
    example.createCriteria().andNameEqualTo("latte");
    example.setOrderByClause("id desc");
    List<Coffee> list = coffeeMapper.selectByExample(example);
    list.forEach(e -> log.info("selectByExample: {}", e));
  }

}

运行数据入库和查询日志如下:

Coffee Coffee 
[Hash = 298057575, id=1, name=espresso, price=CNY 20.00, 
createTime=Sat Sep 07 12:23:08 CST 2019, updateTime=Sat Sep 07 12:23:08 CST 2019]

selectByExample: Coffee
[Hash = 1872515144, id=2, name=latte, price=CNY 30.00, 
createTime=Sat Sep 07 12:23:08 CST 2019, updateTime=Sat Sep 07 12:23:08 CST 2019]


总结

恭喜你,学会了Mybatis生成工具Generator的应用
代码下载:

https://github.com/zgpeace/Spring-Boot2.1/tree/master/db/demodbmybatisgenerator

参考

http://www.mybatis.org/generator/index.html

https://github.com/geektime-geekbang/geektime-spring-family/tree/master/Chapter%203/mybatis-generator-demo

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值