前言
这里介绍JPA中使用Page进行分页及分页的封装,前端传递的参数类型如下形式:
?start=10&count=5
结果展示如下:
环境
SpringBoot 2.5.3 + JPA 2.5.3
具体实现
import com.coisini.springbootlearn.model.Product;
import com.coisini.springbootlearn.model.common.PageCounter;
import com.coisini.springbootlearn.model.common.Paging;
import com.coisini.springbootlearn.repository.ProductRepository;
import com.coisini.springbootlearn.util.CommonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/product")
public class ProductController {
@Autowired
private ProductRepository productRepository;
/**
* 获取商品分页数据
* @return
*/
@GetMapping("/getPageProduct")
public Paging<Product> getPageSpu(@RequestParam(defaultValue = "0") Integer start,
@RequestParam(defaultValue = "2") Integer count) {
// 分页参数构造
PageCounter pageCounter = CommonUtil.convertToPageParameter(start, count);
// 构造分页查询信息
Pageable page = PageRequest.of(pageCounter.getPage(), pageCounter.getCount(), Sort.by("id").descending());
// 查询分页结果
Page<Product> pageResult = productRepository.findAll(page);
// 返回分页构造对象
return new Paging<>(pageResult);
}
}
/**
* @Description Product 仓储
* @author coisini
* @date Aug 14, 2021
* @Version 1.0
*/
@Repository
public interface ProductRepository extends JpaRepository<Product, Long> {
}
/**
* @Description Product 模型
* @author coisini
* @date Aug 15, 2021
* @Version 1.0
*/
@Entity
@Getter
@Setter
public class Product {
@Id
private int id;
private String title;
}
import com.coisini.springbootlearn.model.common.PageCounter;
/**
* @Description 公用工具类
* @author coisini
* @Version 1.0
*/
public class CommonUtil {
/**
* page参数转换
* @param start
* @param count
*/
public static PageCounter convertToPageParameter(Integer start, Integer count) {
int pageNum = start / count;
return PageCounter.builder()
.page(pageNum)
.count(count)
.build();
}
}
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.springframework.data.domain.Page;
import java.util.List;
/**
* @Description 分页返回对象
* @author coisini
* @date Aug 15, 2021
* @Version 1.0
*/
@Getter
@Setter
@NoArgsConstructor
public class Paging<T> {
/**
* 总数量
*/
private Long total;
/**
* 当前请求数量
*/
private Integer count;
/**
* 当前页码
*/
private Integer page;
/**
* 总页码
*/
private Integer totalPage;
/**
* 数据
*/
private List<T> data;
/**
* 构造函数
*/
public Paging(Page<T> pageData) {
this.initPageParameters(pageData);
}
/**
* 构造分页参数
* @param pageData
*/
void initPageParameters(Page<T> pageData) {
this.total = pageData.getTotalElements();
this.count = pageData.getSize();
this.page = pageData.getNumber();
this.totalPage = pageData.getTotalPages();
this.data = pageData.getContent();
}
}
- 接口访问
- End -
﹀
﹀
﹀
梦想是咸鱼
关注一下吧
|