# 核心功能

# 🧂条件构造器

除了新增以外,修改、删除、查询的 SQL 语句都需要指定 where 条件。因此 BaseMapper 中提供的相关方法除了以 id 作为 where 条件以外,还支持更加复杂的 where 条件。

image.png

参数中的 Wrapper 就是条件构造的抽象类,其下有很多默认实现,继承关系如图:

image.png

Wrapper 的子类 AbstractWrapper 提供了 where 中包含的所有条件构造方法:

image.png

而 QueryWrapper 在 AbstractWrapper 的基础上拓展了一个 select 方法,允许指定查询字段:

image.png

而 UpdateWrapper 在 AbstractWrapper 的基础上拓展了一个 set 方法,允许指定 SQL 中的 SET 部分:
image.png

# 🧂Service 接口

MybatisPlus 不仅提供了 BaseMapper,还提供了通用的 Service 接口及默认实现,封装了一些常用的 service 模板方法。
通用接口为 IService ,默认实现为 ServiceImpl ,其中封装的方法可以分为以下几类:

  • save :新增
  • remove :删除
  • update :更新
  • get :查询单个结果
  • list :查询集合结果
  • count :计数
  • page :分页查询

# 🧂CRUD

新增

image.png

  • save 是新增单个元素
  • saveBatch 是批量新增
  • saveOrUpdate 是根据 id 判断,如果数据存在就更新,不存在则新增
  • saveOrUpdateBatch 是批量的新增或修改

删除:

image.png

  • removeById :根据 id 删除
  • removeByIds :根据 id 批量删除
  • removeByMap :根据 Map 中的键值对为条件删除
  • remove(Wrapper<T>) :根据 Wrapper 条件删除
  • ~~removeBatchByIds~~ :暂不支持

修改:

image.png

  • updateById :根据 id 修改
  • update(Wrapper<T>) :根据 UpdateWrapper 修改, Wrapper 中包含 setwhere 部分
  • update(T,Wrapper<T>) :按照 T 内的数据修改与 Wrapper 匹配到的数据
  • updateBatchById :根据 id 批量修改

Get:
image.png

  • getById :根据 id 查询 1 条数据
  • getOne(Wrapper<T>) :根据 Wrapper 查询 1 条数据
  • getBaseMapper :获取 Service 内的 BaseMapper 实现,某些时候需要直接调用 Mapper 内的自定义 SQL 时可以用这个方法获取到 Mapper

List:
image.png

  • listByIds :根据 id 批量查询
  • list(Wrapper<T>) :根据 Wrapper 条件查询多条数据
  • list() :查询所有

Count
image.png

  • count() :统计所有数量
  • count(Wrapper<T>) :统计符合 Wrapper 条件的数据数量

getBaseMapper
当我们在 service 中要调用 Mapper 中自定义 SQL 时,就必须获取 service 对应的 Mapper,就可以通过这个方法:
image.png

# 基本用法