MongoRepository 实现分页查询
时间: 2024-01-27 09:05:18 浏览: 94
MongoRepository 可以通过继承 PagingAndSortingRepository 接口来实现分页查询。具体步骤如下:
1. 在 Repository 接口中继承 PagingAndSortingRepository 接口:
```java
import org.springframework.data.repository.PagingAndSortingRepository;
public interface UserRepository extends PagingAndSortingRepository<User, String> {
}
```
2. 在 Service 层中调用 Repository 的方法,并传入 Pageable 对象来实现分页查询:
```java
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
@Service
public class UserService {
private final UserRepository userRepository;
public UserService(UserRepository userRepository) {
this.userRepository = userRepository;
}
public Page<User> findAll(Pageable pageable) {
return userRepository.findAll(pageable);
}
}
```
3. 在 Controller 中调用 Service 的方法,并传入 Pageable 对象来接收分页查询结果:
```java
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 UserController {
private final UserService userService;
public UserController(UserService userService) {
this.userService = userService;
}
@GetMapping("/users")
public Page<User> getUsers(@RequestParam(value = "page", defaultValue = "0") int page,
@RequestParam(value = "size", defaultValue = "10") int size) {
PageRequest pageRequest = PageRequest.of(page, size);
return userService.findAll(pageRequest);
}
}
```
以上是基于 Spring Data MongoDB 和 MongoRepository 实现分页查询的一个示例。
阅读全文