mybatis 多表分页
时间: 2025-02-09 15:03:41 浏览: 29
### 使用 MyBatis 实现多表分页查询
为了实现基于 MyBatis 的多表分页查询,可以采用 `PageHelper` 组件来简化分页逻辑。下面是一个完整的解决方案,涵盖了从项目配置到具体代码实现的过程。
#### 配置依赖项
首先,在项目的 pom.xml 文件中加入 PageHelper 的 Maven 依赖:
```xml
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.4.6</version>
</dependency>
```
此依赖会自动集成 PageHelper 到 Spring Boot 应用程序中[^2]。
#### 创建 Mapper 接口
定义两个实体类对应的 Mapper 接口,假设有一个用户表 (`users`) 和产品表 (`products`),其中产品表关联着用户 ID (`uid`) 字段。创建相应的 Mapper 接口如下所示:
```java
@Mapper
public interface ProductMapper {
/**
* 根据学生ID获取对应的产品列表.
*/
@Select("SELECT p.* FROM products p JOIN users u ON p.uid = u.id WHERE u.id = #{uid}")
List<Product> selectProductsByUserId(@Param("uid") Long userId);
}
```
对于用户的分页查询,则可以在另一个 Mapper 中定义方法签名并利用 `PageHelper.startPage()` 方法来进行分页处理:
```java
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.ibatis.annotations.Param;
@Mapper
public interface UserMapper {
/**
* 用户按颜色筛选的分页查询.
*/
IPage<User> selectUserPages(Page<User> page, String color);
}
```
注意这里使用了 MyBatis Plus 提供的 `IPage<T>` 类型作为返回值类型以便更好地支持分页操作[^3]。
#### 编写 Service 层业务逻辑
接下来编写服务层代码调用上述 Mapper 进行实际的数据访问,并完成分页封装工作:
```java
@Service
public class UserServiceImpl implements UserService {
private final UserMapper userMapper;
private final ProductMapper productMapper;
public UserServiceImpl(UserMapper userMapper, ProductMapper productMapper) {
this.userMapper = userMapper;
this.productMapper = productMapper;
}
@Override
public PageInfo<UserDTO> getUsersWithPagination(int pageNum, int pageSize, String filterColor) {
// 开始分页
PageHelper.startPage(pageNum, pageSize);
// 执行带过滤条件的颜色查询
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
if (filterColor != null && !"".equals(filterColor.trim())) {
queryWrapper.eq("color", filterColor);
}
List<User> userList = userMapper.selectList(queryWrapper);
// 将结果集转换成 DTO 并填充额外信息(如关联的产品)
List<UserDTO> dtoList = userList.stream()
.map(user -> {
UserDTO dto = new UserDTO();
BeanUtils.copyProperties(user, dto);
// 获取该用户下的所有产品
List<Product> productList = productMapper.selectProductsByUserId(user.getId());
dto.setProducts(productList);
return dto;
})
.collect(Collectors.toList());
// 返回带有总条数等元数据的结果对象
return new PageInfo<>(dtoList);
}
}
```
在这个例子中,先启动分页插件再执行数据库查询语句是非常重要的,因为这决定了最终 SQL 语句里 LIMIT 子句的位置和参数传递方式。
阅读全文
相关推荐


















