MyBatis-Plus 深度解析:IService 接口全指南
关键词:MyBatis-Plus、IService、ServiceImpl、CRUD、Java、ORM
一、什么是 IService?
com.baomidou.mybatisplus.extension.service.IService<T>
是 MyBatis-Plus 提供的 通用 Service 层接口,用于封装常见的 CRUD 操作,简化业务逻辑层的开发。
它是 MyBatis-Plus 三层架构封装 的一部分:
层级 | MyBatis-Plus 封装 |
---|---|
Controller | 无封装,自行编写 |
Service | IService<T> + ServiceImpl<M, T> |
Mapper | BaseMapper<T> |
二、核心功能概览
IService<T>
提供了 30+ 个常用方法,覆盖单表操作的 90% 场景:
类别 | 方法示例 | 说明 |
---|---|---|
插入 | save(T) / saveBatch(List<T>) | 单条或批量插入 |
删除 | removeById() / remove(Wrapper) | 按 ID 或条件删除 |
更新 | updateById() / update(Wrapper) | 按 ID 或条件更新 |
查询 | getById() / list() / page() | 单条、列表、分页 |
统计 | count() / count(Wrapper) | 总记录数或条件统计 |
存在 | exist(Wrapper) | 判断是否存在记录 |
三、快速上手
1. 实体类
@Data
public class User {private Long id;private String name;private Integer age;
}
2. Mapper 接口
@Mapper
public interface UserMapper extends BaseMapper<User> {
}
3. Service 接口
public interface UserService extends IService<User> {// 可扩展自定义方法
}
4. Service 实现类
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>implements UserService {// 自动拥有 IService 的所有实现
}
5. 使用示例
@RestController
@RequestMapping("/user")
public class UserController {@Autowiredprivate UserService userService;@GetMapping("/{id}")public User get(@PathVariable Long id) {return userService.getById(id);}@PostMappingpublic boolean add(@RequestBody User user) {return userService.save(user);}@GetMapping("/page")public IPage<User> page(@RequestParam int current, @RequestParam int size) {return userService.page(new Page<>(current, size));}
}
四、IService 方法全景图(含重载)
以下方法均以
default
实现,可直接调用。
方法签名 | 说明 |
---|---|
boolean save(T entity) | 插入一条记录 |
boolean saveBatch(Collection<T> entityList) | 批量插入(默认批次大小 1000) |
boolean saveBatch(Collection<T> list, int batchSize) | 指定批次大小 |
boolean removeById(Serializable id) | 按 ID 删除 |
boolean removeByMap(Map<String,Object> columnMap) | 按字段 Map 删除 |
boolean remove(Wrapper<T> queryWrapper) | 按条件删除 |
boolean updateById(T entity) | 按 ID 更新 |
boolean update(T entity, Wrapper<T> updateWrapper) | 按条件更新 |
T getById(Serializable id) | 按 ID 查询 |
T getOne(Wrapper<T> queryWrapper) | 按条件查询一条 |
List<T> list() | 查询所有 |
List<T> list(Wrapper<T> queryWrapper) | 按条件查询列表 |
IPage<T> page(IPage<T> page) | 无条件分页 |
IPage<T> page(IPage<T> page, Wrapper<T> queryWrapper) | 按条件分页 |
int count() | 总记录数 |
int count(Wrapper<T> queryWrapper) | 按条件统计 |
boolean exist(Wrapper<T> queryWrapper) | 判断是否存在 |
五、与 ServiceImpl 的关系
接口 | 实现类 | 说明 |
---|---|---|
IService<T> | 仅定义方法 | 无实现,需配合 ServiceImpl |
ServiceImpl<M extends BaseMapper<T>, T> | 提供所有 IService 的默认实现 | 泛型指定 Mapper 和实体 |
✅ 最佳实践:
自定义 Service 接口继承IService<T>
,实现类继承ServiceImpl<YourMapper, T>
并实现自定义接口。
六、自定义扩展:在 Service 中写复杂业务
public interface UserService extends IService<User> {/*** 根据姓名模糊查询并分页*/IPage<User> searchByName(String keyword, int current, int size);
}
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>implements UserService {@Overridepublic IPage<User> searchByName(String keyword, int current, int size) {LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();wrapper.like(User::getName, keyword);return page(new Page<>(current, size), wrapper);}
}
七、事务支持
IService
的所有方法默认 未加事务,如需事务,请在 实现类方法 上加 @Transactional
:
@Transactional(rollbackFor = Exception.class)
public boolean transferMoney(Long from, Long to, BigDecimal amount) {// 自定义业务
}
八、性能与批量操作建议
场景 | 建议 |
---|---|
批量插入 | 使用 saveBatch(list, 500) ,控制批次大小 |
大批量更新 | 避免循环 updateById ,考虑手写 SQL 或 MP 的 UpdateWrapper |
分页查询 | 使用 Page<T> 对象,MP 自动执行 count 和 limit |
避免 N+1 | 关联查询使用 @TableField(el = "...") 或 VO + 手写 SQL |
九、常见问题 FAQ
问题 | 解答 |
---|---|
可以不加 Mapper 吗? | 不可以,ServiceImpl 需要 BaseMapper 才能工作 |
可以多个实体复用一个 Service 吗? | 不建议,一个 IService<T> 对应一个实体 |
可以注入原生 SqlSession 吗? | 可以,通过 baseMapper.getSqlStatement() 或 @Autowired SqlSessionFactory |
可以切换数据源吗? | 可以,配合动态数据源插件(如 dynamic-datasource-spring-boot-starter ) |
十、总结:一句话记住 IService
IService<T>
是 MyBatis-Plus 提供的 Service 层“神器”,让你 不写 SQL、不写重复 CRUD,专注业务逻辑,配合ServiceImpl
即可一键拥有强大且可扩展的 Service 层。
十一、参考资料
- MyBatis-Plus 官方文档:https://baomidou.com
- GitHub 源码:https://github.com/baomidou/mybatis-plus
- 示例项目:https://gitee.com/baomidou/mybatis-plus-samples