在Java中,Pageable接口通常用于处理分页数据
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String email;
// Getters and Setters, Constructors
}
JpaRepository
和JpaSpecificationExecutor
:public interface UserRepository extends JpaRepository<User, Long>, JpaSpecificationExecutor<User> {
}
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
public Page<User> findAllUsers(Pageable pageable) {
return userRepository.findAll(pageable);
}
public Page<User> findUsersByName(String name, Pageable pageable) {
Specification<User> specification = (root, query, criteriaBuilder) ->
criteriaBuilder.equal(root.get("name"), name);
return userRepository.findAll(specification, pageable);
}
}
@RestController
@RequestMapping("/users")
public class UserController {
@Autowired
private UserService userService;
@GetMapping
public ResponseEntity<Page<User>> getAllUsers(
@RequestParam(defaultValue = "0") int page,
@RequestParam(defaultValue = "10") int size) {
Pageable pageable = PageRequest.of(page, size);
Page<User> users = userService.findAllUsers(pageable);
return ResponseEntity.ok(users);
}
@GetMapping("/search")
public ResponseEntity<Page<User>> searchUsersByName(
@RequestParam String name,
@RequestParam(defaultValue = "0") int page,
@RequestParam(defaultValue = "10") int size) {
Pageable pageable = PageRequest.of(page, size);
Page<User> users = userService.findUsersByName(name, pageable);
return ResponseEntity.ok(users);
}
}
在这个例子中,我们创建了一个简单的用户管理系统,包括实体类、Repository接口、Service类和Controller类。我们使用Pageable
接口处理分页数据,并通过PageRequest.of()
方法创建Pageable
对象。在Controller类中,我们使用@RequestParam
注解获取分页参数,并将其传递给Service方法。这是一个典型的Java分页实践案例。