Springboot jpa之分页查询Pageable

本文介绍了在Springboot中使用JPA进行分页查询时,如何利用PageRequest替代已过时的Pageable构造方式。内容强调了PageRequest的参数设置,包括页码从0开始和每页大小需大于等于1的要求。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

    /**
     * 将MySQL的limit的offset、limit参数转化为Pageable的page、size,同时加入排序字段properties
     * @param limit 个数
     * @param offset 偏移量
     * @param properties 排序字段
     * @return
     */
    public static Pageable getPageable(Integer limit,
                                       Integer offset,
                                       String properties) {
        int page = offset / limit;
        int size = limit;
        Sort sort = new Sort(Sort.Direction.ASC, properties);
        return PageRequest.of(page, size, sort);
    }

注意:
1、Pageable pageable = new Pageable(page, size, sort)已经过时,可以使用Pageable pageable = PageRequest.of(page, size, sort)代替

2、注意参数的类型,其中size要大于等于1,page则是从0开始算起。

在Spring Boot中,可以使用JPA实现分页查询。下面是一个示例代码: 首先,确保已经添加了Spring Data JPA的依赖。 ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> ``` 然后,在你的Repository接口中,继承`PagingAndSortingRepository`接口,并传入实体类和主键类型。 ```java import org.springframework.data.repository.PagingAndSortingRepository; public interface YourRepository extends PagingAndSortingRepository<YourEntity, Long> { } ``` 接下来,在你的Service或Controller中,注入该Repository,并使用`Pageable`对象来实现分页查询。 ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; @Service public class YourService { @Autowired private YourRepository yourRepository; public Page<YourEntity> getAllEntities(Pageable pageable) { return yourRepository.findAll(pageable); } } ``` 最后,可以在Controller中接收分页参数,并调用Service层的方法进行分页查询。 ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; @RestController public class YourController { @Autowired private YourService yourService; @GetMapping("/entities") public Page<YourEntity> getEntities(@RequestParam(defaultValue = "0") int page, @RequestParam(defaultValue = "10") int size) { return yourService.getAllEntities(PageRequest.of(page, size)); } } ```
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值