一、mybatis的分頁
1、PageHelper的使用
(1)導入依賴
<!-- 分頁查詢依賴 -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.2.12</version>
</dependency>
(2)mvc的service層
PageHelper.startPage(page, size);
List<Demo> demoByParams= demoMapper
.getDemoByParams(ids.toString(), name, desc, type);
PageInfo<Demo> pageInfo = new PageInfo<>(demoByParams);
result.setData(pageInfo.getList());
result.setTotal(pageInfo.getTotal());
(3)mvc的mapper層
和分頁無關,原sql
import org.apache.ibatis.annotations.Param;
List<Demo> getDemoByParams(@Param("ids") String ids, @Param("name") String name,
@Param("desc") String desc, @Param("type") int type);
二、jpa分頁
1、org.springframework.data.domain.PageRequest;的使用
(1)mvc的Service層
//jpa自帶查詢方法分頁使用:多傳一個參數pageRequest
PageRequest pageRequest = PageRequest.of(page - 1, size);//特别注意:jpa目前頁從0開始,但前端一般參數從1開始
Page<JctbctYjjbntPy> findAll = basicFarmlandPageRepository.findAll(pageRequest);
result.setData(findAll.getContent());//擷取分頁後的資料
result.setTotal(findAll.getTotalElements());//擷取總數量
//自定義jpa的sql查詢
PageRequest pageRequest = PageRequest.of(page - 1, size);
Page<JctbctYjjbntPy> byZjCodeList = basicFarmlandPageRepository.getByZjCodeList(code, pageRequest);
result.setData(byZjCodeList.getContent());
result.setTotal(byZjCodeList.getTotalElements());
(2)mvc的repository層
import org.springframework.data.repository.query.Param;
import org.springframework.data.domain.Page;
@Query("SELECT t FROM JctbctYjjbntPy t WHERE xzdm=?1")
Page<JctbctYjjbntPy> getByZjCodeList(@Param("code") String code, PageRequest pageRequest);