springboot jpa 分页查询
时间: 2023-11-05 21:57:27 浏览: 130
在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));
}
}
```
阅读全文