天天看点

mybatis和jpa分页的实现一、mybatis的分页二、jpa分页

一、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);