spring-boot-data-jpa、JPA实现分页
spring-boot-data-jpa、JPA实现分页
JPA越来越丰富了,下面使用springboot3.x实现JPA分页
通过传入PageRequest pageRequest = PageRequest.of(page, size);到接口查询,返回Page拿到分页数据。
转自 https://lingkang.top/archives/jpa-shi-xian-fen-ye
依赖
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-jpa</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-security</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>com.mysql</groupId><artifactId>mysql-connector-j</artifactId><scope>runtime</scope></dependency>
数据库配置
spring.jpa.show-sql=true
spring.jpa.open-in-view=false
spring.jpa.hibernate.ddl-auto=update
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&nullCatalogMeansCurrent=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.hikari.maximum-pool-size=10
spring.datasource.hikari.poolName=db1
启动类
@SpringBootApplication
@EnableJpaRepositories("top.lingkang.lingdongmall.repository")
@EntityScan("top.lingkang.lingdongmall.entity")
public class LingdongMallApplication {public static void main(String[] args) {SpringApplication.run(LingdongMallApplication.class, args);}}
接口
public interface GoodsRepository extends JpaRepository<GoodsEntity, String> {@Query("select e from GoodsClassifyEntity c left join GoodsEntity e on e.id=c.goodsId " +"where c.classifyId=?1 and c.level=?2")Page<GoodsEntity> goods(String classifyId, String level, Pageable pageable);
}
调用
public ResponseResultPage goods(String classifyId, String level, Integer page, Integer size) {// 注意,page分页是从0开始计算的,0=第一页PageRequest pageRequest = PageRequest.of(page, size);Page<GoodsEntity> goods = goodsRepository.goods(classifyId, level, pageRequest);return new ResponseResultPage().setPage(page).setSize(size).setTotal(goods.getTotalElements()) // 分页总数.setData(goods.getContent()); // 分页查询到内容}