分页插件PageHelper

来源:互联网 发布:淘宝代付申请超限 编辑:程序博客网 时间:2024/06/06 16:35

我们在开发管理系统的时候,一般都会用到分页功能。今天我初次接触到PageHelper分页插件,感觉挺好用的,在此和大家分享一下。
第一步:在pom文件引入PageHelper的jar包依赖。

<dependency>    <groupId>com.github.pagehelper</groupId>    <artifactId>pagehelper</artifactId>    <version>3.4.2</version></dependency>

第二步:需要在SqlMapConfig.xml中配置插件。

<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE configuration        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"        "http://mybatis.org/dtd/mybatis-3-config.dtd"><configuration>    <!-- 配置分页插件 -->    <plugins>        <plugin interceptor="com.github.pagehelper.PageHelper">            <!-- 设置数据库类型 Oracle,Mysql,MariaDB,SQLite,Hsqldb,PostgreSQL六种数据库-->                    <property name="dialect" value="mysql"/>        </plugin>    </plugins></configuration>

第三步:在查询的sql语句执行之前,添加一行代码:

PageHelper.startPage(page, rows);

第一个参数page表示要显示第几页。
第二个参数rows表示每页显示的记录数。
第四步:获取查询结果的总数量。
创建一个PageInfo类的对象,从对象中获取分页信息。

下面我分享下PageHelper在项目中各层的具体实现。
由于Easyui中datagrid控件要求的数据格式为

{total:”2”,rows:[{“id”:”1”,”name”,”张三”},{“id”:”2”,”name”,”李四”}]}

形式,所以我们自定义EUDataGridResult对象作为返回值pojo。

Controller层:

@RequestMapping("/item/list")@ResponseBodypublic EUDataGridResult getItemList(Integer page, Integer rows) {    EUDataGridResult result = itemService.getItemList(page, rows);    return result;}

Service层:

@Overridepublic EUDataGridResult getItemList(int page, int rows) {    // 查询商品列表    TbItemExample example = new TbItemExample();    // 分页处理    PageHelper.startPage(page, rows);    List<TbItem> list = itemMapper.selectByExample(example);    // 创建一个返回值对象    EUDataGridResult result = new EUDataGridResult();    result.setRows(list);    // 取记录总条数    PageInfo<TbItem> pageInfo = new PageInfo<>(list);    result.setTotal(pageInfo.getTotal());    return result;}

EUDataGridResult:

package com.taotao.common.pojo;import java.util.List;public class EUDataGridResult {    private long total;    private List<?> rows;    public long getTotal() {        return total;    }    public void setTotal(long total) {        this.total = total;    }    public List<?> getRows() {        return rows;    }    public void setRows(List<?> rows) {        this.rows = rows;    }}

这样我们在浏览器输入http://localhost:8080/item/list?page=1&rows=3便可以看到分页效果。

1 0
原创粉丝点击