源本科技 | 码上会

Db Kit

2026/04/02
0
0

引言

Db Kit 是 MyBatis-Plus 提供的一个静态工具类com.baomidou.mybatisplus.core.toolkit.Db)。

它的核心价值在于:无需注入 Mapper/Service,直接通过静态方法调用 CRUD,完美解决 Spring 中常见的循环依赖问题,让工具类、静态方法、非 Spring 管理类中操作数据库变得极其简单。


定位与优势

核心作用

  • 静态调用:直接 Db.getById(),不用 @Autowired

  • 解耦:彻底摆脱 Service/Mapper 注入依赖

  • 万能:任何类、任何地方都能直接操作数据库

  • 防循环依赖:传统 A 依赖 B、B 依赖 A 的死循环彻底解决

方式对比

方式

需要注入

解决循环依赖

使用难度

Mapper

❌ 不能

Service

❌ 不能

ActiveRecord

否(需继承 Model)

✅ 能

Db Kit

✅ 完美解决

极低


前置条件

  1. MP 版本:3.5.0+

  2. 必须存在对应 Mapper 每个实体必须写一个继承 BaseMapper<T> 的 Mapper,并被 Spring 扫描到

  3. 无需任何配置,直接用


基础用法

查询

// 根据 ID 查询
User user = Db.getById(1L, User.class);

// 根据 ID 批量查询
List<User> userList = Db.listByIds(List.of(1L,2L,3L), User.class);

// 条件查询 list
List<User> list = Db.lambdaQuery(User.class)
        .eq(User::getStatus, 1)
        .list();

// 查询单个
User user = Db.lambdaQuery(User.class)
        .eq(User::getId,1L)
        .one();

// 查询数量
long count = Db.count(Wrappers.lambdaQuery(User.class));

新增

// 新增
boolean save = Db.save(user);

// 批量新增
boolean batchSave = Db.saveBatch(userList);

// 批量新增(指定批次)
boolean batchSave = Db.saveBatch(userList, 100);

更新

// 根据 ID 更新
boolean update = Db.updateById(user);

// 条件更新
boolean update = Db.lambdaUpdate(User.class)
        .set(User::getAge, 20)
        .eq(User::getId, 1L)
        .update();

删除

// 根据 ID 删除
boolean remove = Db.removeById(1L, User.class);

// 条件删除
boolean remove = Db.remove(Wrappers.lambdaQuery(User.class).eq(User::getId,1L));

链式写法

lambdaQuery

推荐

List<User> list = Db.lambdaQuery(User.class)
        .eq(User::getStatus, 1)
        .gt(User::getAge, 18)
        .orderByDesc(User::getCreateTime)
        .list();

lambdaUpdate

boolean update = Db.lambdaUpdate(User.class)
        .set(User::getEmail, "test@qq.com")
        .eq(User::getId, 1L)
        .update();

优势

  • 类型安全

  • 无硬编码

  • 不用创建 Wrapper 对象

  • 一行完成


核心价值

解决循环依赖

传统问题

AService → 注入 BService BService → 注入 AService → 循环依赖报错

解决方案

不用注入!直接静态调用:

@Service
public class AService {
    public void test() {
        // 直接使用,无需注入 BService
        List<B> list = Db.list(B.class);
    }
}

彻底告别循环依赖


常用方法

查询

  • getById(id, clazz)

  • listByIds(ids, clazz)

  • list(wrapper)

  • lambdaQuery(clazz)

  • count(wrapper)

  • one(wrapper)

新增

  • save(entity)

  • saveBatch(collection)

  • saveBatch(collection, batchSize)

更新

  • updateById(entity)

  • update(entity, wrapper)

  • lambdaUpdate(clazz)

删除

  • removeById(id, clazz)

  • remove(wrapper)


注意事项

  1. 必须有 Mapper 即使不注入,也必须存在,否则找不到 SQL 会报错

  2. 必须传 实体 classDb.getById(1L, User.class)

  3. 循环中禁止频繁调用 循环内每次都获取连接,性能极差

  4. 批量操作必须用 batch 方法

  5. 事务依然有效 方法上加 @Transactional 即可

  6. 多租户、逻辑删除、自动填充全部生效 与 Service 效果完全一致