溫馨提示×

SpringBoot怎么對數(shù)據(jù)進(jìn)行分頁查詢

小億
102
2024-01-19 17:21:37
欄目: 編程語言

在SpringBoot中,可以使用Spring Data JPA提供的PagingAndSortingRepository接口來實現(xiàn)分頁查詢。

首先,在你的Repository接口中繼承PagingAndSortingRepository接口,并指定實體類和主鍵類型。例如,如果你要對名為User的實體進(jìn)行分頁查詢,可以創(chuàng)建一個UserRepository接口如下:

@Repository
public interface UserRepository extends PagingAndSortingRepository<User, Long> {
}

接下來,在你的Service類中注入UserRepository,并使用Pageable接口來指定分頁參數(shù)。Pageable接口有許多實現(xiàn)類,其中最常用的是PageRequest類。你可以創(chuàng)建一個PageRequest對象,指定頁數(shù)、每頁的數(shù)據(jù)量和排序規(guī)則。

@Service
public class UserService {
    @Autowired
    private UserRepository userRepository;
    
    public Page<User> getUsers(int pageNo, int pageSize, String sortBy) {
        Pageable pageable = PageRequest.of(pageNo, pageSize, Sort.by(sortBy));
        return userRepository.findAll(pageable);
    }
}

在上述代碼中,getUsers方法接受三個參數(shù):pageNo表示要查詢的頁數(shù),pageSize表示每頁的數(shù)據(jù)量,sortBy表示排序規(guī)則。創(chuàng)建了一個PageRequest對象,并使用userRepository.findAll(pageable)方法進(jìn)行查詢。

最后,你可以在Controller層調(diào)用UserService中的getUsers方法來獲取分頁數(shù)據(jù),并將其返回給前端。

@RestController
@RequestMapping("/users")
public class UserController {
    @Autowired
    private UserService userService;
    
    @GetMapping
    public ResponseEntity<Page<User>> getUsers(
            @RequestParam(defaultValue = "0") int pageNo,
            @RequestParam(defaultValue = "10") int pageSize,
            @RequestParam(defaultValue = "id") String sortBy) {
        Page<User> page = userService.getUsers(pageNo, pageSize, sortBy);
        return ResponseEntity.ok(page);
    }
}

上述代碼中,getUsers方法接受三個可選的請求參數(shù):pageNo表示要查詢的頁數(shù),默認(rèn)為0,pageSize表示每頁的數(shù)據(jù)量,默認(rèn)為10,sortBy表示排序規(guī)則,默認(rèn)按照id排序。調(diào)用userService.getUsers方法獲取分頁數(shù)據(jù),并將其包裝在ResponseEntity對象中返回給前端。

這樣,在訪問/users接口時,就能獲取分頁查詢的結(jié)果了。例如,訪問/users?pageNo=0&pageSize=10&sortBy=name,將返回第一頁、每頁10條數(shù)據(jù),按照name字段排序的結(jié)果。

0