springboot+mybatis使用PageHelper分頁


項目結構和spring搭建mybatis請參考springboot整合mybatis。在這個基礎上配置分頁。

一:導入PageHelper依賴

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

二:在啟動類SpringmybatisdemoApplication中配置PageHelper bean

@Bean
	public PageHelper pageHelper() {
		System.out.println("MyBatisConfiguration.pageHelper()");
		PageHelper pageHelper = new PageHelper();
		Properties p = new Properties();
		p.setProperty("offsetAsPageNum", "true");
		p.setProperty("rowBoundsWithCount", "true");
		p.setProperty("reasonable", "true");
		pageHelper.setProperties(p);
		return pageHelper;
	}

三:在controller中使用PageHelper ,注入對應的服務UserService (該服務的具體可看本文章開頭的springboot整合mybatis).注意:只有緊接着PageHelper.startPage(2,3); 后的那句sql才會進行分頁,再下一句sql則不分頁。特別注意的是,下面獲取到的結果是存放在返回的list中的,但是如果直接輸出personList.toString(),輸出的是Page對應(寫的是一個結果的總體信息格式如下Page{count=true, pageNum=2, pageSize=3, startRow=3, endRow=6, total=6, pages=2, countSignal=false, orderBy='name DESC ', orderByOnly=false, reasonable=true, pageSizeZero=false})(因為toString方法被重寫了),需要用循環獲取的方式獲取其中的內容,才可以看到分頁的結果

package com.example.springmybatisdemo.controller;

import com.example.springmybatisdemo.entity.Person;
import com.example.springmybatisdemo.service.UserService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
public class UserController {
    @Autowired
    private UserService userService;

    @RequestMapping("/helloUser/{id}")
    @ResponseBody
    public String selectUser (@PathVariable int id){
        PageHelper.startPage(2,3); //pageNum=2, pageSize=3 ,表示每頁的大小為3,查詢第二頁的結果
        PageHelper.orderBy("name DESC "); //進行分頁結果的排序,name為字段名,排序規則DESC/ASC
        List<Person>personList= userService.selectUser();
        System.out.println(personList.toString()); //輸出的是Page對象
        for(int i=0;i<personList.size();i++){
            System.out.println(personList.get(i)); //獲取到的分頁結果
        }
        return userService.selectUser().toString(); //這句不分頁,又再次執行原始sql語句,正確的是返回list中的結果

    }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM