SprinBoot分页之List转Page

因为分页查询的时候有时需要先组装一个新的类列表之后再转化为Page类,手动写当然也可以,但是springboot已经为我们提供了转换的方法。详细步骤请点击下面的连接

springboot分页List转Page

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
在 Spring Boot 中进行列表分页可以通过使用 Spring Data JPA 和 Pageable 接口来实现。下面是一个简单的示例: 首先,确保你已经添加了 Spring Data JPA 的依赖到你的项目中。 接下来,在你的实体类中添加 `javax.persistence.Entity` 注解,并指定 `@Id` 注解用于标识主键字段。 ```java import javax.persistence.Entity; import javax.persistence.Id; @Entity public class YourEntity { @Id private Long id; // 其他字段和方法... } ``` 然后,创建一个继承自 `JpaRepository` 接口的数据访问层接口。该接口将提供基本的 CRUD 操作和分页查询方法。 ```java import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; @Repository public interface YourRepository extends JpaRepository<YourEntity, Long> { } ``` 现在,在你的服务层或控制器中注入该数据访问层接口,并使用 `Pageable` 来进行分页查询。 ```java import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; @Service public class YourService { private final YourRepository yourRepository; public YourService(YourRepository yourRepository) { this.yourRepository = yourRepository; } public Page<YourEntity> getEntitiesByPage(int pageNumber, int pageSize) { Pageable pageable = PageRequest.of(pageNumber, pageSize); return yourRepository.findAll(pageable); } } ``` 这样,你就可以通过调用 `getEntitiesByPage` 方法来获取指定页码和每页大小的分页数据了。 ```java @GetMapping("/entities") public ResponseEntity<Page<YourEntity>> getEntities( @RequestParam(defaultValue = "0") int pageNumber, @RequestParam(defaultValue = "10") int pageSize) { Page<YourEntity> page = yourService.getEntitiesByPage(pageNumber, pageSize); return ResponseEntity.ok(page); } ``` 以上是一个简单的示例,你可以根据自己的需求进行调整和扩展。希望对你有帮助!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值