目录

Mybatis 通用 Mapper 及插件

使用 MyBatis 一般会引入 Mybatis 的一些增强工具,如 MyBatis-Plus、MyBatis Generator、Fluent MyBatis 等。

通用 Mapper

MyBatis Generator

MyBatis Generator (MBG) 是 MyBatis 的代码生成器。它将为所有版本的 MyBatis 生成代码。它将内省一个数据库表(或许多表),并将生成可用于访问表的工件。这减少了设置对象和配置文件以与数据库表交互的初始麻烦。MBG 试图对大部分简单 CRUD(创建、检索、更新、删除)的数据库操作产生重大影响。您仍然需要为联接查询或存储过程编写 SQL 和对象代码。

MyBatis提供了代码生成器。MyBatis生成器(MyBatis Generator)能对数据库表内省,生成执行的增删改查(英语:Create, read, update and delete)(CRUD)时所需的MyBatis代码。

Fluent MyBatis

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
buildscript {
    ext {
        lombokVersion = '1.18.8'
        fluentMybatisVersion = '1.9.4.1'
    }
}
dependencies {
        compile("com.github.atool:fluent-mybatis:${fluentMybatisVersion}")
        compileOnly("org.projectlombok:lombok:${lombokVersion}")
        compileOnly("com.github.atool:fluent-mybatis-processor:${fluentMybatisVersion}")

        // annotation processor配置
        annotationProcessor("org.projectlombok:lombok:${lombokVersion}")
        annotationProcessor("com.github.atool:fluent-mybatis-processor:${fluentMybatisVersion}")
    }
// https://mvnrepository.com/artifact/com.github.atool/fluent-mybatis
implementation 'com.github.atool:fluent-mybatis:1.9.4.1'
// https://mvnrepository.com/artifact/com.github.atool/fluent-mybatis-processor
implementation 'com.github.atool:fluent-mybatis-processor:1.9.4.1'

MyBatis Dynamic SQL

This library is a framework for generating dynamic SQL statements.

Mybatis Dynamic SQL 被 Mybatis Genrator 很好的支持。 这个库通过实现一个 类似于SQL领域专用语言 (domain-specific language,DSL)来工作,DSL能够创建一个包含完整SQL语句以及语句所需要全部参数的对象。这个对象能够被Mybatis作为传入Mapper方法的参数直接使用。

1
2
3
4
// https://mvnrepository.com/artifact/org.mybatis.dynamic-sql/mybatis-dynamic-sql
implementation 'org.mybatis.dynamic-sql:mybatis-dynamic-sql:1.4.0'
// https://mvnrepository.com/artifact/org.mybatis.generator/mybatis-generator-core
implementation 'org.mybatis.generator:mybatis-generator-core:1.4.1'

动态 SQL 是 MyBatis 的强大特性之一。如果你使用过 JDBC 或其它类似的框架,你应该能理解根据不同条件拼接 SQL 语句有多痛苦,例如拼接时要确保不能忘记添加必要的空格,还要注意去掉列表最后一个列名的逗号。利用动态 SQL,可以彻底摆脱这种痛苦。 在 Mapper XML 中借助 动态 SQL 元素 来实现SQL语句的条件拼接。

  • if
  • choose (when, otherwise)
  • trim (where, set)
  • foreach

MyBatis-Plus

MyBatis-Plus(简称 MP)是一个 MyBatis 的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。 https://baomidou.com/

支持 ActiveRecord 形式调用,实体类只需继承 Model 类即可进行强大的 CRUD 操作

  • 实体类继承Model类
  • 重写pkVal方法
  • 通过实体类直接进行表的简单增删改查操作

通用 Mapper Tk Mybatis

配合分页插件 PageHelper 使用

https://mapper.mybatis.io/ https://github.com/abel533/Mapper

1
2
3
4
// https://mvnrepository.com/artifact/tk.mybatis/mapper-spring-boot-starter
implementation 'tk.mybatis:mapper-spring-boot-starter:4.2.1'
// https://mvnrepository.com/artifact/com.github.pagehelper/pagehelper-spring-boot-starter
implementation 'com.github.pagehelper:pagehelper-spring-boot-starter:1.4.1'