尝试将MyBatis Generator与Spring Boot应用程序结合使用来配置

什么?

我想尝试使用Spring Boot+MyBatis来构建应用,我打算使用MyBatis Generator作为起步。

给我一个只需中文本地化的选择

题目

我们将在Spring Boot应用程序中集成MyBatis,并考虑以下配置作为题目。

    • ModelおよびMapperはMyBatis Generatorを使って自動生成する

MyBatis Generator

MyBatis Generatorは、Mavenプラグインとして組み込む
生成するMyBatisのMapperは、XML Mapperとする
Mapperには@Mapperアノテーションを付与して、MyBatis Spring Boot Starterに自動検出させる

MyBatis Spring Boot Starter / MyBatis Spring Boot AutoConfigure

使用するデータベースはPostgreSQLとする

我们将表格定义如下。

create table pokemon (
  id serial,
  name text,
  primary key(id)
);

create table person (
  id integer,
  last_name text,
  first_name text,
  primary key(id)
);

环境

这次的环境是这样的。

$ java --version
openjdk 11.0.14.1 2022-02-08
OpenJDK Runtime Environment (build 11.0.14.1+1-Ubuntu-0ubuntu1.20.04)
OpenJDK 64-Bit Server VM (build 11.0.14.1+1-Ubuntu-0ubuntu1.20.04, mixed mode, sharing)


$ mvn --version
Apache Maven 3.8.5 (3599d3414f046de2324203b78ddcf9b5e4388aa0)
Maven home: $HOME/.sdkman/candidates/maven/current
Java version: 11.0.14.1, vendor: Ubuntu, runtime: /usr/lib/jvm/java-11-openjdk-amd64
Default locale: ja_JP, platform encoding: UTF-8
OS name: "linux", version: "5.4.0-107-generic", arch: "amd64", family: "unix"

我们使用的是PostgreSQL 14.2版。

$ docker container run \
  -it \
  --rm \
  --name postgres \
  -p 5432:5432 \
  -e POSTGRES_PASSWORD=password \
  postgres:14.2-bullseye

创建Spring Boot项目

$ curl -s https://start.spring.io/starter.tgz \
  -d bootVersion=2.6.6 \
  -d javaVersion=11 \
  -d name=spring-boot-mybatis-generator-demo \
  -d groupId=com.example \
  -d artifactId=com.example \
  -d version=0.0.1-SNAPSHOT \
  -d packageName=com.example.spring.mybatis \
  -d dependencies=mybatis,postgresql \
  -d baseDir=spring-boot-mybatis-generator-demo | tar zxvf -

进入项目内部。

$ cd spring-boot-mybatis-generator-demo

这里可以找到自动生成的依存关系和插件设置。

	<properties>
		<java.version>11</java.version>
	</properties>
	<dependencies>
		<dependency>
			<groupId>org.mybatis.spring.boot</groupId>
			<artifactId>mybatis-spring-boot-starter</artifactId>
			<version>2.2.2</version>
		</dependency>

		<dependency>
			<groupId>org.postgresql</groupId>
			<artifactId>postgresql</artifactId>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

我只是添加了数据库连接设置。

spring.datasource.url=jdbc:postgresql://localhost:5432/postgres
spring.datasource.username=postgres
spring.datasource.password=password

在项目中添加MyBatis Generator工具

在pom.xml中加入MyBatis Generator。

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
			<plugin>
				<groupId>org.mybatis.generator</groupId>
				<artifactId>mybatis-generator-maven-plugin</artifactId>
				<version>1.4.1</version>
				<configuration>
					<configurationFile>${project.basedir}/src/main/resources/generatorConfig.xml</configurationFile>
					<overwrite>true</overwrite>
					<includeAllDependencies>true</includeAllDependencies>
				</configuration>
			</plugin>
		</plugins>
	</build>

文件在这里。

 

配置文件的内容与默认值相同,但是明确写有MyBatis Generator的配置文件是为了标明。

通过将overwrite设置为true并将includeAllDependencies设置为true,可以启用自动生成结果的覆盖,并使其能够引用运行时范围中的PostgreSQL JDBC驱动程序的依赖关系。

如果不喜欢使用includeAllDependencies,可以通过在插件的依赖中添加PostgreSQL的JDBC驱动程序来解决。

			<plugin>
				<groupId>org.mybatis.generator</groupId>
				<artifactId>mybatis-generator-maven-plugin</artifactId>
				<version>1.4.1</version>
				<configuration>
					<configurationFile>${project.basedir}/src/main/resources/generatorConfig.xml </configurationFile>
					<overwrite>true</overwrite>
					<!-- <includeAllDependencies>true</includeAllDependencies> -->
				</configuration>
				<dependencies>
					<dependency>
						<groupId>org.postgresql</groupId>
						<artifactId>postgresql</artifactId>
						<version>${postgresql.version}</version>
					</dependency>
				</dependencies>
			</plugin>

这是MyBatis Generator的配置。

<?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="tables" targetRuntime="MyBatis3">
        <plugin type="org.mybatis.generator.plugins.EqualsHashCodePlugin"/>
        <plugin type="org.mybatis.generator.plugins.MapperAnnotationPlugin"/>

        <jdbcConnection
                driverClass="org.postgresql.Driver"
                connectionURL="jdbc:postgresql://localhost:5432/postgres"
                userId="postgres"
                password="password"/>

        <javaModelGenerator
                targetPackage="com.example.spring.mybatis.model"
                targetProject="src/main/java"/>
        <sqlMapGenerator
                targetPackage="com.example.spring.mybatis.mapper"
                targetProject="src/main/resources"/>
        <javaClientGenerator
                type="XMLMAPPER"
                targetPackage="com.example.spring.mybatis.mapper"
                targetProject="src/main/java"/>

        <table tableName="pokemon">
            <generatedKey column="id" sqlStatement="JDBC"/>
        </table>
        <table tableName="person"/>
    </context>
</generatorConfiguration>

在使用XML Mapper之前的前提条件是将targetRuntime设置为MyBatis3。

 

    <context id="tables" targetRuntime="MyBatis3">

为了给生成的Mapper添加@Mapper注解,我们将应用org.mybatis.generator.plugins.MapperAnnotationPlugin插件。

 

        <plugin type="org.mybatis.generator.plugins.EqualsHashCodePlugin"/>
        <plugin type="org.mybatis.generator.plugins.MapperAnnotationPlugin"/>

org.mybatis.generator.plugins.EqualsHashCodePlugin插件是附带的,它自动为模型生成equals和hashCode方法。

模型、Mapper XML文件和Mapper的生成。

        <javaModelGenerator
                targetPackage="com.example.spring.mybatis.model"
                targetProject="src/main/java"/>
        <sqlMapGenerator
                targetPackage="com.example.spring.mybatis.mapper"
                targetProject="src/main/resources"/>
        <javaClientGenerator
                type="XMLMAPPER"
                targetPackage="com.example.spring.mybatis.mapper"
                targetProject="src/main/java"/>

通过指定XMLMAPPER,会生成一个Mapper对象,以便使用Mapper XML。

 

然后,指定要自动生成的表格。

        <table tableName="pokemon">
            <generatedKey column="id" sqlStatement="JDBC"/>
        </table>
        <table tableName="person"/>

generatedKey是用于自动为主键编号的。

现在开始执行。

$ mvn mybatis-generator:generate

产生结果。

$ tree src/main/java/com/example/spring/mybatis/{mapper,model} src/main/resources/com/exampl
e/spring/mybatis/mapper
src/main/java/com/example/spring/mybatis/mapper
├── PersonMapper.java
└── PokemonMapper.java
src/main/java/com/example/spring/mybatis/model
├── Person.java
├── PersonExample.java
├── Pokemon.java
└── PokemonExample.java
src/main/resources/com/example/spring/mybatis/mapper
├── PersonMapper.xml
└── PokemonMapper.xml

0 directories, 8 files

Mapper接口上有@Mapper注解。

@Mapper
public interface PokemonMapper {

通过MyBatis Spring Boot Starter的AutoConfigure,现在可以认识到Mapper。

尝试移动一下

既然使用了MyBatis Generator完成自动化生成,我们可以简单使用一下进行操作确认。

创建这样一个类。

package com.example.spring.mybatis;

import com.example.spring.mybatis.mapper.PersonMapper;
import com.example.spring.mybatis.mapper.PokemonMapper;
import com.example.spring.mybatis.model.Person;
import com.example.spring.mybatis.model.Pokemon;
import com.example.spring.mybatis.model.PokemonExample;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

@Component
public class DemoRunner implements ApplicationRunner {
    Logger logger = LoggerFactory.getLogger(DemoRunner.class);

    PokemonMapper pokemonMapper;
    PersonMapper personMapper;

    public DemoRunner(PokemonMapper pokemonMapper, PersonMapper personMapper) {
        this.pokemonMapper = pokemonMapper;
        this.personMapper = personMapper;
    }

    @Transactional
    @Override
    public void run(ApplicationArguments args) throws Exception {
        Pokemon pikachu = new Pokemon();
        pikachu.setName("ピカチュウ");
        pokemonMapper.insert(pikachu);

        logger.info("pikachu id = {}", pikachu.getId());

        Pokemon fushigidane = new Pokemon();
        fushigidane.setName("フシギダネ");
        pokemonMapper.insert(fushigidane);

        pokemonMapper
                .selectByExample(new PokemonExample())
                .forEach(pokemon -> logger.info("pokemon[{}]: {}", pokemon.getId(), pokemon.getName()));

        Person tanjiro = new Person();
        tanjiro.setId(1);
        tanjiro.setLastName("竈門");
        tanjiro.setFirstName("炭治郎");

        personMapper.insert(tanjiro);

        Person result = personMapper.selectByPrimaryKey(1);
        logger.info("person[{}]: {} {}", result.getId(), result.getLastName(), result.getFirstName());
    }
}

我会试着动一下。

$ mvn spring-boot:run

结果。

2022-04-08 20:56:32.355  INFO 141382 --- [           main] com.example.spring.mybatis.DemoRunner    : pikachu id = 1
2022-04-08 20:56:32.382  INFO 141382 --- [           main] com.example.spring.mybatis.DemoRunner    : pokemon[1]: ピカチュウ
2022-04-08 20:56:32.383  INFO 141382 --- [           main] com.example.spring.mybatis.DemoRunner    : pokemon[2]: フシギダネ
2022-04-08 20:56:32.388  INFO 141382 --- [           main] com.example.spring.mybatis.DemoRunner    : person[1]: 竈門 炭治郎

删除日期和时间,并使其更加清晰易读。

pokemon[1]: ピカチュウ
pokemon[2]: フシギダネ
person[1]: 竈門 炭治郎

好的,没问题。

虽然很简单,就这样吧。

bannerAds