在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分頁實踐案例。