JAVA-SSM学习12 MyBatisPlus-IService接口

みんなと出会えたこと嬉しくて

IService接口

如果Mapper持久层可以简化的话,那么Service逻辑处理层代码同样也可以简化。这需要使用IService接口

IService接口通常指的是 ‌MyBatis-Plus‌ 框架中提供的通用Service层接口。它封装了常用的单表 CRUD(增删改查)操作、批量操作以及条件查询等功能,旨在简化Service层的开发,减少重复代码。

其关键在于需要实现:

继承BaseMapper<T>的Mapper接口
继承IService<T>的Service接口
实现Service接口的ServiceImpl实现类

@Mapper
public interface UserMapper extends BaseMapper<User> {
}

public interface UserService extends IService<User> {
}

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
}

IService接口方法

常见方法如下:

新增(Save)

boolean save(T entity):保存一条记录。
boolean saveBatch(Collection<T> entityList):批量保存,默认批次大小为 1000。必要时可通过在JDBC连接语句添加rewriteBatchedStatements=true提升性能
boolean saveOrUpdate(T entity):根据 ID 判断是新增还是更新。

删除 (Remove)

boolean removeById(Serializable id):根据 ID 删除。
boolean removeByIds(Collection<? extends Serializable> idList):根据 ID 集合批量删除(生成 IN 语句)。
boolean remove(Wrapper<T> queryWrapper):根据条件构造器删除。

注意‌:对于大量数据删除或特定数据库限制(如 Oracle IN 子句限制),可使用removeBatchByIds,它会分批执行删除操作以避免报错。

修改 (Update)

boolean updateById(T entity):根据 ID 更新非空字段。
boolean update(T entity, Wrapper<T> updateWrapper):根据条件构造器更新。

查询 (Get/List/Page)

T getById(Serializable id):根据 ID 查询单个对象。
List<T> list():查询所有列表。
List<T> list(Wrapper<T> queryWrapper):根据条件查询列表。
IPage<T> page(IPage<T> page, Wrapper<T> queryWrapper):分页查询。
long count():查询总记录数。

posted @ 2026-04-25 12:03  tcswuzb  阅读(80)  评论(0)    收藏  举报