Spring+Mybatis: PageHelper分页插件配置与使用教程

版权申诉
5星 · 超过95%的资源 2 下载量 160 浏览量 更新于2024-09-12 收藏 54KB PDF 举报
本文档详细讲解了如何在Spring+SpringMVC+Mybatis的开发环境中集成和使用Mybatis分页插件PageHelper。首先,我们需要注意的是,由于PageHelper插件在版本5.0之后进行了升级,配置时应使用PageInterceptor而不是PageHelper。在项目的pom.xml文件中,你需要添加PageHelper的依赖,版本为5.1.2,如下: ```xml <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper</artifactId> <version>5.1.2</version> </dependency> ``` 配置全局配置是在mybatis的`mybatis-config.xml`文件中进行的。在这里,你需要添加一个`<plugins>`标签,并指定插件拦截器为`com.github.pagehelper.PageInterceptor`。配置项中,`reasonable`属性用于控制分页的合理性,如果设置为`true`,则在pageNum小于等于0时自动跳转到第一页,大于总页数时跳转到最后一页。 接下来是实际的使用部分。例如,当你需要实现对用户表的多条件查询时,你可能会有一个名为`User`的模型类,如: ```java import java.util.Date; public class User { private Integer id; private String name; private Date createdAt; // 其他属性... // getter和setter方法... } ``` 在进行分页查询时,你可以创建一个Mapper接口,比如`UserMapper`,并使用`PageHelper`的动态查询方法,例如`selectList()`,如下所示: ```java import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import org.apache.ibatis.annotations.Select; public interface UserMapper { @Select("SELECT * FROM user WHERE condition1 = #{condition1} AND condition2 = #{condition2}") PageInfo<User> getUserList(@Param("condition1") String condition1, @Param("condition2") String condition2); } ``` 在Service层或Controller层,你可以这样调用这个方法并获取分页结果: ```java @Autowired private UserMapper userMapper; List<User> userList = userMapper.getUserList(condition1, condition2); int totalPages = userMapper.getTotalPages(); // 获取总页数 int currentPage = userMapper.getCurrentPage(); // 获取当前页码 ``` 通过这种方式,你可以方便地在Mybatis查询中实现动态分页,提高代码的可维护性和灵活性。这无疑是一个提升开发效率和用户体验的重要工具。