springboot+mybatis 使用分页插件PageHelper步骤记录

分页是平常开发中是十分常见的需要,虽然原理不难,但是自己写起来就很麻烦。

所以,记录一下springboot + mybatis 使用分页插件PageHelper 的步骤:

1.在pom.xml中引入依赖:

<!--分页插件-->
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper</artifactId>
            <version>5.0.0</version>
        </dependency>
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper-spring-boot-autoconfigure</artifactId>
            <version>1.2.3</version>
        </dependency>
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper-spring-boot-starter</artifactId>
            <version>1.2.3</version>
        </dependency>
        <!--分页插件-->

2.在application.propreties或者application.yml中加入配置:


#分页插件
pagehelper.helperDialect=mysql
pagehelper.reasonable=true
pagehelper.supportMethodsArguments=true
pagehelper.params=count=countSql
#分页插件
pagehelper:
  helper-dialect: mysql
  reasonable: true
  support-methods-arguments: true
  params: count=countSql

3.在controller层中使用(也可以在service层中):

 

@RequestMapping("/agentList")
public ModelAndView agentList(HttpServletRequest request, Integer pageNum, Integer      
 pageSize) throws Exception {

        ModelAndView mv = new ModelAndView("myAgent");

        User user = (User) request.getSession().getAttribute("user");
        if(pageNum == null){
            pageNum = 1;
        }
        if(pageSize == null){
            pageSize = 6;
        }
        //使用分页插件
        PageHelper.startPage(pageNum , pageSize);

        List<Map> list = agentService.agentList(user.getId()); //获取后台数据列表(根据自己系统修改)

        //根据查询的数据列表,得到分页的结果对象
        PageInfo<Map> pageList = new PageInfo<Map>(list); 
        List<Map> datas = pageList.getList(); 
        mv.addObject("datas", datas);
        return mv;
    }

其中我在使用的时候,发现有个地方需要注意:  获取后台数据列表的这句话 List<Map> agentList = as.agentList(user.getId());    一定要放在PageHelper.startPage(pageNum , pageSize);  这句话的后边,否则查询的分页效果无效。

引入依赖,加入配置,就可以使用了,在此记录一下。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章