spring boot 整合MyBatis Generator自动生成动态sql代码

2022-05-12 21:45:26 浏览数 (1)

一、背景

最近使用mybatis时,看到一篇文章使用yml配置来简化MyBatis Generator默认使用的xml配置,就想着使用人家提供的MyBatis Generator去自动生成一些bean,动态mapper文件。

项目整合地址: https://github.com/xujiankang6/study/tree/main/spring-boot-research

二、实践

1、maven里面添加该插件

(1)configurationFile属性为MyBatis Generator的配置yml文件路径。

代码语言:javascript复制
        <plugin>
            <groupId>io.github.javthon</groupId>
            <artifactId>mybatis-generator-yml-maven-plugin</artifactId>
            <version>0.0.1</version>
            <configuration>
                <configurationFile>src/main/resources/generator/generatorConfig.yml</configurationFile>
            </configuration>
        </plugin>
2、generatorConfig.yml配置文件

(1)配置如下

代码语言:javascript复制
mybatisGenerator:
  datasource:
    type: mysql
    address: localhost:3306
    db: test?serverTimezone=GMT
    driver-class-name: com.mysql.jdbc.Driver
    username: root
    password: 123456

  targetPackage:
    model: com.example.demo.model
    mapper: com.example.demo.mapper
    javaXmlFilesSamePackage: true

  targetRuntime: MyBatis3DynamicSql
  mapperSuffixName: mapper
  java8: false
  disableExample: true

  plugins:
    comment: true
    lombok: false
    swagger: false
    mapperAnnotation: false
    serializable: false

  tables:
    - user

(2)主要属性说明

属性

类型

默认值

是否必须

描述

datasource

Map

数据库的连接信息, 见下方的"数据源配置"

targetPackage

Map

生成代码的包路径,见下方targetPackage配置

targetRuntime

String

MyBatis3

mybatis generator生产代码的格式,见下方targetRuntime可选项

mapperSuffixName

String

mapper

mapper类或xml文件的后缀名,如果将此属性设置为dao,并且表名是user,它将生成UserDao.java和UserDao.xml,如果targetRuntime设置为MyBatis3DynamicSql,则此属性将不起作用

java8

Boolean

false

如果为true,则生成模型日期字段将使用Java8的LocalDateTime或LocalDate,否则使用Date

disableExample

Boolean

true

此属性仅在targetRuntime为MyBatis3生效,为true时mapper不生成"by example"代码

plugins

Map

配置是否开启注释, lombok, swagger, mapperAnnotation, serializable等插件, 详情见下方插件配置

tables

List

多个表格名,配置方式见generatorConfig.yml样例

(3)更多配置看该插件git仓库

https://github.com/javthon/mybatis-generator-yml-maven-plugin/blob/master/Readme-CN.md

(4)目前只支持sqlserver,mysql,oracle。

(5)注意上面db的配置需要在数据库名后加该属性?serverTimezone=GMT,否则会报下面错误:

[ERROR] The server time zone value '�й���׼ʱ��' is unrecognized or represents more than one time zone. You must configure either the server or JDBC driver (via the 'serverTimezone' configuration property) to use a more specifc time zone value if you want to utilize time zone support.

3、通过idea执行该插件

(1)可以多次执行,每次执行覆盖上次生成的代码。

4、查看结果

(1)自动生成的bean文件如下:

代码语言:javascript复制
public class User {
    /**
     */
    @Generated("org.mybatis.generator.api.MyBatisGenerator")
    private Integer uid;

    /**
     */
    @Generated("org.mybatis.generator.api.MyBatisGenerator")
    private String uname;

    /**
     */
    @Generated("org.mybatis.generator.api.MyBatisGenerator")
    private String upwd;

    @Generated("org.mybatis.generator.api.MyBatisGenerator")
    public Integer getUid() {
        return uid;
    }

    @Generated("org.mybatis.generator.api.MyBatisGenerator")
    public void setUid(Integer uid) {
        this.uid = uid;
    }

    @Generated("org.mybatis.generator.api.MyBatisGenerator")
    public String getUname() {
        return uname;
    }

    @Generated("org.mybatis.generator.api.MyBatisGenerator")
    public void setUname(String uname) {
        this.uname = uname;
    }

    @Generated("org.mybatis.generator.api.MyBatisGenerator")
    public String getUpwd() {
        return upwd;
    }

    @Generated("org.mybatis.generator.api.MyBatisGenerator")
    public void setUpwd(String upwd) {
        this.upwd = upwd;
    }
}

(2)自动生成的mapper文件如下:

代码语言:javascript复制
@Mapper
public interface UserMapper {
    @Generated("org.mybatis.generator.api.MyBatisGenerator")
    BasicColumn[] selectList = BasicColumn.columnList(uid, uname, upwd);

    @Generated("org.mybatis.generator.api.MyBatisGenerator")
    @SelectProvider(type=SqlProviderAdapter.class, method="select")
    long count(SelectStatementProvider selectStatement);

    @Generated("org.mybatis.generator.api.MyBatisGenerator")
    @DeleteProvider(type=SqlProviderAdapter.class, method="delete")
    int delete(DeleteStatementProvider deleteStatement);

    @Generated("org.mybatis.generator.api.MyBatisGenerator")
    @InsertProvider(type=SqlProviderAdapter.class, method="insert")
    int insert(InsertStatementProvider<User> insertStatement);

    @Generated("org.mybatis.generator.api.MyBatisGenerator")
    @InsertProvider(type=SqlProviderAdapter.class, method="insertMultiple")
    int insertMultiple(MultiRowInsertStatementProvider<User> multipleInsertStatement);

    @Generated("org.mybatis.generator.api.MyBatisGenerator")
    @SelectProvider(type=SqlProviderAdapter.class, method="select")
    @Results(id="UserResult", value = {
        @Result(column="uid", property="uid", jdbcType=JdbcType.INTEGER, id=true),
        @Result(column="uname", property="uname", jdbcType=JdbcType.VARCHAR),
        @Result(column="upwd", property="upwd", jdbcType=JdbcType.VARCHAR)
    })
    Optional<User> selectOne(SelectStatementProvider selectStatement);

    @Generated("org.mybatis.generator.api.MyBatisGenerator")
    @SelectProvider(type=SqlProviderAdapter.class, method="select")
    @Results(id="UserResult", value = {
        @Result(column="uid", property="uid", jdbcType=JdbcType.INTEGER, id=true),
        @Result(column="uname", property="uname", jdbcType=JdbcType.VARCHAR),
        @Result(column="upwd", property="upwd", jdbcType=JdbcType.VARCHAR)
    })
    List<User> selectMany(SelectStatementProvider selectStatement);

    @Generated("org.mybatis.generator.api.MyBatisGenerator")
    @UpdateProvider(type=SqlProviderAdapter.class, method="update")
    int update(UpdateStatementProvider updateStatement);

    @Generated("org.mybatis.generator.api.MyBatisGenerator")
    default long count(CountDSLCompleter completer) {
        return MyBatis3Utils.countFrom(this::count, user, completer);
    }

    @Generated("org.mybatis.generator.api.MyBatisGenerator")
    default int delete(DeleteDSLCompleter completer) {
        return MyBatis3Utils.deleteFrom(this::delete, user, completer);
    }

    @Generated("org.mybatis.generator.api.MyBatisGenerator")
    default int deleteByPrimaryKey(Integer uid_) {
        return delete(c -> 
            c.where(uid, isEqualTo(uid_))
        );
    }

    @Generated("org.mybatis.generator.api.MyBatisGenerator")
    default int insert(User record) {
        return MyBatis3Utils.insert(this::insert, record, user, c ->
            c.map(uid).toProperty("uid")
            .map(uname).toProperty("uname")
            .map(upwd).toProperty("upwd")
        );
    }

    @Generated("org.mybatis.generator.api.MyBatisGenerator")
    default int insertMultiple(Collection<User> records) {
        return MyBatis3Utils.insertMultiple(this::insertMultiple, records, user, c ->
            c.map(uid).toProperty("uid")
            .map(uname).toProperty("uname")
            .map(upwd).toProperty("upwd")
        );
    }

    @Generated("org.mybatis.generator.api.MyBatisGenerator")
    default int insertSelective(User record) {
        return MyBatis3Utils.insert(this::insert, record, user, c ->
            c.map(uid).toPropertyWhenPresent("uid", record::getUid)
            .map(uname).toPropertyWhenPresent("uname", record::getUname)
            .map(upwd).toPropertyWhenPresent("upwd", record::getUpwd)
        );
    }

    @Generated("org.mybatis.generator.api.MyBatisGenerator")
    default Optional<User> selectOne(SelectDSLCompleter completer) {
        return MyBatis3Utils.selectOne(this::selectOne, selectList, user, completer);
    }

    @Generated("org.mybatis.generator.api.MyBatisGenerator")
    default List<User> select(SelectDSLCompleter completer) {
        return MyBatis3Utils.selectList(this::selectMany, selectList, user, completer);
    }

    @Generated("org.mybatis.generator.api.MyBatisGenerator")
    default List<User> selectDistinct(SelectDSLCompleter completer) {
        return MyBatis3Utils.selectDistinct(this::selectMany, selectList, user, completer);
    }

    @Generated("org.mybatis.generator.api.MyBatisGenerator")
    default Optional<User> selectByPrimaryKey(Integer uid_) {
        return selectOne(c ->
            c.where(uid, isEqualTo(uid_))
        );
    }

    @Generated("org.mybatis.generator.api.MyBatisGenerator")
    default int update(UpdateDSLCompleter completer) {
        return MyBatis3Utils.update(this::update, user, completer);
    }

    @Generated("org.mybatis.generator.api.MyBatisGenerator")
    static UpdateDSL<UpdateModel> updateAllColumns(User record, UpdateDSL<UpdateModel> dsl) {
        return dsl.set(uid).equalTo(record::getUid)
                .set(uname).equalTo(record::getUname)
                .set(upwd).equalTo(record::getUpwd);
    }

    @Generated("org.mybatis.generator.api.MyBatisGenerator")
    static UpdateDSL<UpdateModel> updateSelectiveColumns(User record, UpdateDSL<UpdateModel> dsl) {
        return dsl.set(uid).equalToWhenPresent(record::getUid)
                .set(uname).equalToWhenPresent(record::getUname)
                .set(upwd).equalToWhenPresent(record::getUpwd);
    }

    @Generated("org.mybatis.generator.api.MyBatisGenerator")
    default int updateByPrimaryKey(User record) {
        return update(c ->
            c.set(uname).equalTo(record::getUname)
            .set(upwd).equalTo(record::getUpwd)
            .where(uid, isEqualTo(record::getUid))
        );
    }

    @Generated("org.mybatis.generator.api.MyBatisGenerator")
    default int updateByPrimaryKeySelective(User record) {
        return update(c ->
            c.set(uname).equalToWhenPresent(record::getUname)
            .set(upwd).equalToWhenPresent(record::getUpwd)
            .where(uid, isEqualTo(record::getUid))
        );
    }

(3)自动生成的mapper支持类如下:

代码语言:javascript复制
public final class UserDynamicSqlSupport {
    @Generated("org.mybatis.generator.api.MyBatisGenerator")
    public static final User user = new User();

    @Generated("org.mybatis.generator.api.MyBatisGenerator")
    public static final SqlColumn<Integer> uid = user.uid;

    @Generated("org.mybatis.generator.api.MyBatisGenerator")
    public static final SqlColumn<String> uname = user.uname;

    @Generated("org.mybatis.generator.api.MyBatisGenerator")
    public static final SqlColumn<String> upwd = user.upwd;

    @Generated("org.mybatis.generator.api.MyBatisGenerator")
    public static final class User extends SqlTable {
        public final SqlColumn<Integer> uid = column("uid", JDBCType.INTEGER);

        public final SqlColumn<String> uname = column("uname", JDBCType.VARCHAR);

        public final SqlColumn<String> upwd = column("upwd", JDBCType.VARCHAR);

        public User() {
            super("user");
        }
    }
}
5、项目整合中用到的mybatis相关maven依赖如下
代码语言:javascript复制
    <dependency>
        <groupId>org.mybatis.spring.boot</groupId>
        <artifactId>mybatis-spring-boot-starter</artifactId>
        <version>2.0.1</version>
    </dependency>
    <dependency>
        <groupId>org.mybatis.spring.boot</groupId>
        <artifactId>mybatis-spring-boot</artifactId>
        <version>2.0.1</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.mybatis.dynamic-sql/mybatis-dynamic-sql -->
    <dependency>
        <groupId>org.mybatis.dynamic-sql</groupId>
        <artifactId>mybatis-dynamic-sql</artifactId>
        <version>1.3.0</version>
    </dependency>

    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.35</version>
    </dependency>

三、总结

以上就是实现spring boot 整合MyBatis Generator自动生成动态sql代码所有内容,希望能够帮到大家

https://github.com/xujiankang6/study/tree/main/spring-boot-research

0 人点赞