这两天在学习项目的时候,发现有一个开源的mybatis分页插件,通过该插件可以很简单的实现分页查询的功能。大概总结了一下步骤。
1.首先在pom.xml中添加:
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.1.2</version>
</dependency>
PageHelper除了本身的jar包外,它还依赖了一个叫jsqlparser的jar包,使用时,我们不需要单独指定jsqlparser的maven依赖,maven的间接依赖会帮我们引入。
2.在spring-mybatis.xml中添加:
<!-- spring和MyBatis整合,不需要mybatis的配置映射文件 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<!-- 自动扫描mapping.xml文件 -->
<property name="mapperLocations" value="classpath:com/draeger/mapping/*.xml"></property>
<!--pageHelper-->
<property name="plugins">
<array>
<bean class="com.github.pagehelper.PageInterceptor">
<property name="properties">
<!--使用下面的方式配置参数,一行配置一个 -->
<value>
reasonable=true
</value>
</property>
</bean>
</array>
</property>
</bean>
3.在controller中:
//分页查询
@RequestMapping("/pageList")
public PageInfo<DeviceFun> pageList(int pageNo,int pageSize,String status){
return applicationService.queryPageList(pageNo, pageSize, status);
}
4.在Service中:
//分页查询
public ArrayList<DeviceFun> queryPageList(int pageNo,int pageSize);
5.在ServiceImpl中:
@Override
public PageInfo<DeviceFun> queryPageList(Integer pageNo,Integer pageSize,String status){
//页码pageNo,每页显示记录数pageSize
pageNo = pageNo == null?1:pageNo;
pageSize = pageSize == null?10:pageSize;
//测试输出
System.out.println("pageNo:"+pageNo+";pageSize:"+pageSize);
//设置页码和每页显示记录数
PageHelper.startPage(pageNo, pageSize);
//创建List,调用查询接口
ArrayList<DeviceFun> deviceFun = new ArrayList<DeviceFun>();
deviceFun = applicationDao.pageList();//获取所有设备信息
//用PageInfo对结果进行包装
PageInfo<DeviceFun> page = new PageInfo<DeviceFun>(deviceFun);
return page;
}
6.在Dao中:
//分页查询
public ArrayList<DeviceFun> pageList();
7.在Mapper中:
<!-- 查询表单接口 -->
<select id="pageList" resultMap="com.×××项目名.model.DeviceFun">
select * from [DeviceFun]
</select>
注意:PageHelper5.x版本和4.x版本之前的配置是有区别的,列如:5.x版本在spring-mybatis.xml中不需要配置数据库方言dialect。如果分页异常,可以试着在sql语句中追加: ORDER BY D_Id DESC。
pageHelper大概有两种使用方法:
1.第一种,直接通过RowBounds参数完成分页查询 。
List<Student> list = studentMapper.find(new RowBounds(0, 10));
Page page = ((Page) list;
2.第二种,PageHelper.startPage()静态方法
//获取第1页,10条内容,默认查询总数count
PageHelper.startPage(1, 10);
//紧跟着的第一个select方法会被分页
List<Country> list = studentMapper.find();
Page page = ((Page) list;
注意:返回结果list,已经是Page对象,Page对象是一个ArrayList。
原理:使用ThreadLocal来传递和保存Page对象,每次查询,都需要单独设置PageHelper.startPage()方法。