Mybatis plus:IService接口

一、介绍

在MybatisPlus框架中,IService接口扮演着重要的角色。作为一个通用的服务接口,IService定义了一系列方法,包括查询、插入、更新、删除等。这些方法的定义使得在服务层进行数据库操作变得更为便捷和高效。

  • IService 接口是一个泛型接口,定义了一组通用的基础方法,包括常见的增删改查操作。例如,它提供了插入数据、根据主键更新数据、根据主键删除数据、根据主键查询数据等方法的签名。用户可以根据自己的需求和业务逻辑在自定义的服务接口中继承 IService 接口,并实现其中的方法。用法:
java 复制代码
 public interface UserService extends IService<User> {}
  • ServiceImpl 类是 IService 接口的默认实现类,提供了基本的增删改查操作的实现细节。它使用了泛型参数来规范实体类和主键类型,并实现了 IService 接口中定义的方法。用户可以继承 ServiceImpl 类,并在自己的实现类中添加或重写更具体的业务逻辑。用法:
java 复制代码
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {}

二、IService用法

1、添加数据

java 复制代码
// 插入一条记录(选择字段,策略插入)
boolean save(T entity);

// 插入(批量)
boolean saveBatch(Collection<T> entityList);

// 插入(批量,限制数量)
boolean saveBatch(Collection<T> entityList, int batchSize);

// TableId 注解存在更新记录,否则插入一条记录
boolean saveOrUpdate(T entity);

// 根据 updateWrapper 尝试更新,否则继续执行 saveOrUpdate(T) 方法
boolean saveOrUpdate(T entity, Wrapper<T> updateWrapper);

// 批量修改插入
boolean saveOrUpdateBatch(Collection<T> entityList);

// 批量修改插入
boolean saveOrUpdateBatch(Collection<T> entityList, int batchSize);

可以开启 rewriteBatchedStatements=true 参数,提高批处理的执行效率。

2、删除数据

java 复制代码
// 根据 entity 条件,删除记录
boolean remove(Wrapper<T> queryWrapper);

// 根据 ID 删除
boolean removeById(Serializable id);

// 根据 columnMap 条件,删除记录
boolean removeByMap(Map<String, Object> columnMap);

// 删除(根据ID 批量删除)
boolean removeByIds(Collection<? extends Serializable> idList);

3、修改数据

java 复制代码
// 根据 UpdateWrapper 条件更新记录,需要设置sqlset
boolean update(Wrapper<T> updateWrapper);

// 根据 whereWrapper 条件,更新记录
boolean update(T updateEntity, Wrapper<T> whereWrapper);

// 根据 ID 选择修改
boolean updateById(T entity);

// 根据ID 批量更新
boolean updateBatchById(Collection<T> entityList);

// 根据ID 批量更新
boolean updateBatchById(Collection<T> entityList, int batchSize);

4、查询数据

查询一条数据

java 复制代码
// 根据 ID 查询
T getById(Serializable id);

// 根据 Wrapper,查询一条记录。结果集如果是多个会抛出异常,随机取一条加上限制条件 wrapper.last("LIMIT 1")
T getOne(Wrapper<T> queryWrapper);

// 根据 Wrapper,查询一条记录,这个是方法返回结果不止一条则会抛出异常,如果想默认取第一条结果,可以给这方法传第二个参数为false。
T getOne(Wrapper<T> queryWrapper, boolean throwEx);

// 根据 Wrapper,查询一条记录
Map<String, Object> getMap(Wrapper<T> queryWrapper);

// 根据 Wrapper,查询一条记录
// mapper:转换函数,用于将查询结果中的每个对象转换为指定的对象类型。
<V> V getObj(Wrapper<T> queryWrapper, Function<? super Object, V> mapper);

查询多条数据

java 复制代码
// 查询所有
List<T> list();

// 查询列表
List<T> list(Wrapper<T> queryWrapper);

// 查询(根据 ID 批量查询)
Collection<T> listByIds(Collection<? extends Serializable> idList);

// 查询(根据 columnMap 条件)
Collection<T> listByMap(Map<String, Object> columnMap);

// 查询所有列表
List<Map<String, Object>> listMaps();

// 查询列表
List<Map<String, Object>> listMaps(Wrapper<T> queryWrapper);

// 查询全部记录
List<Object> listObjs();

// 查询全部记录
<V> List<V> listObjs(Function<? super Object, V> mapper);

// 根据 Wrapper 条件,查询全部记录
List<Object> listObjs(Wrapper<T> queryWrapper);

// 根据 Wrapper 条件,查询全部记录
// mapper:转换函数,用于将查询结果中的每个对象转换为指定的对象类型。
<V> List<V> listObjs(Wrapper<T> queryWrapper, Function<? super Object, V> mapper);

查询记录数 count()

java 复制代码
// 查询总记录数
int count();

// 根据 Wrapper 条件,查询总记录数
int count(Wrapper<T> queryWrapper);

分页:Page

java 复制代码
// 无条件分页查询
IPage<T> page(IPage<T> page);

// 条件分页查询
IPage<T> page(IPage<T> page, Wrapper<T> queryWrapper);

// 无条件分页查询
IPage<Map<String, Object>> pageMaps(IPage<T> page);

// 条件分页查询
IPage<Map<String, Object>> pageMaps(IPage<T> page, Wrapper<T> queryWrapper);

IPage 是MyBatis-Plus 提供的一个分页相关的接口,它有一个实现类为 Page,类中定义了分页相关的多个参数。

  • size(每页显示条数):此参数通常由前端传给我们,然后再封装到Page对象中进行分页查询;
  • current(要展示哪一页数据):此参数通常由前端传给我们,然后再封装到Page对象中进行分页查询;
  • orders(排序规则集合):按照哪些字段进行排序?可以为多个,例如希望通过时间进行排序,如果时间相同就根据用户ID降序排序,可以添加多个字段;
  • total(总记录数):指查询完毕后返回的数据库中总记录数,注意不包含已被逻辑删除的数据;
  • records(查询到的分页结果集数据):分页查询得到的多条数据会存储在 records 中,可以看出该对象是一个集合,可以传递一个泛型,泛型就是查询到的数据对应的实体泛型;
java 复制代码
public class Page<T> implements IPage<T> {
    private static final long serialVersionUID = 8545996863226528798L;
    protected List<T> records;
    protected long total;
    protected long size;
    protected long current;
    protected List<OrderItem> orders;
    protected boolean optimizeCountSql;
    protected boolean searchCount;
    protected boolean optimizeJoinOfCountSql;
    protected String countId;
    protected Long maxLimit;
/* 以下省略 */
}

Page对象使用演示:

java 复制代码
@SpringBootTest
public class ProductMapperTest {
    // 自动注入 productMapper 接口对应的实现类对象
    @Autowired
    private ProductMapper productMapper;
    @Test
    public void testPageQuery(){
        // 创建分页查询相关参数 page,泛型为 Product,表示查询到的结果对应的实体类为Product
        Page<Product> page = new Page<>();
        // 设置分页查询显示第二页的数据,实际开发过程中该参数有前端传递
        page.setCurrent(2);
        // 设置分页查询每页显示四条数据,实际开发过程中该参数有前端传递
        page.setSize(4);
        // 创建排序字段集合,不想排序不加即可,实际开发过程中一般都会要求按照时间降序排序
        List<OrderItem> orders = new ArrayList<>();
        // 按照价格排序,排序方式为降序,ASC为True表示升序,false表示降序,第一个参数表示数据库中的列名
        orders.add(new OrderItem("price",false));
        // 按照生产时间排序,排序方式为降序
        orders.add(new OrderItem("production_date",false));
        // 将排序对象集合加入分页查询对象Page中
        page.setOrders(orders);
        // 执行分页查询,可以创建一个Page对象接受查询结果,
        // 也可以用查询条件参数page,但其实最后结果都是同一个
        page = productMapper.selectPage(page, null);
        // 可以新创建一个Page对象,就像下面这样
        Page<Product> productPage = productMapper.selectPage(page,null);
        // 输出分页查询结果显示当前的哪一页
        System.out.println(page.getCurrent());
        // 输出分页查询结果的总数据条数
        System.out.println(page.getTotal());
        // 输出分页查询结果的数据集合
        System.out.println(page.getRecords());
        // 输出分页查询结果的每页显示条数
        System.out.println(page.getSize());
        // 判断刚才分页查询的两个结果对象是否为同一个
        System.out.println(page == productPage);
        // 输出第一个分页查询对象内存地址
        System.out.println(page);
        // 输出第二个分页查询对象内存地址
        System.out.println(productPage);
    }
}

链式

链式查询演示:

java 复制代码
// 链式查询 普通
QueryChainWrapper<T> query();

// 链式查询 lambda 式。注意:不支持 Kotlin
LambdaQueryChainWrapper<T> lambdaQuery();

// 示例:
// eq 指定条件
query().eq("column", value).one();
lambdaQuery().eq(Entity::getId, value).list();

链式更新演示:

java 复制代码
// 链式更改 普通
UpdateChainWrapper<T> update();

// 链式更改 lambda 式。注意:不支持 Kotlin
LambdaUpdateChainWrapper<T> lambdaUpdate();

// 示例:
// eq 指定条件
update().eq("column", value).remove();
lambdaUpdate().eq(Entity::getId, value).update(entity);
相关推荐
郭小李14 小时前
mybatis 动态 sql
java·sql·mybatis
知守观14 小时前
技术考古:iBATIS 2.3.4 时代的持久层,是如何用 Map 玩转 307 个存储过程的?
java·后端·mybatis
captain37615 小时前
MyBatis Plus(1)
java·服务器·mybatis
代码不停20 小时前
MyBatis进阶
spring boot·mybatis
captain3761 天前
MyBatis(入门5)其他查询操作
java·数据库·spring boot·mybatis
captain3761 天前
MyBatis(进阶1)
mybatis
郭小李2 天前
mybatis的 Mapper.xml语法
xml·java·mybatis
m0_639906942 天前
MyBatis 实现分页查询|逻辑分页、物理分页、PageHelper 原理
mybatis
captain3762 天前
MyBatis操作数据库(入门2)
java·数据库·spring boot·后端·spring·mybatis
正儿八经的少年4 天前
MyBatis 一对一、一对多 SQL
数据库·sql·mybatis