溫馨提示×

如何在JPA中實(shí)現(xiàn)MySQL的分頁查詢

小樊
96
2024-08-19 03:01:36
欄目: 云計(jì)算

在JPA中實(shí)現(xiàn)MySQL的分頁查詢可以通過使用Spring Data JPA提供的Pageable接口來實(shí)現(xiàn)。下面是一個(gè)簡單的示例代碼:

首先,在Repository接口中定義一個(gè)方法,使用Pageable作為參數(shù)來實(shí)現(xiàn)分頁查詢:

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;

public interface UserRepository extends JpaRepository<User, Long> {
    Page<User> findAll(Pageable pageable);
}

然后在Service層中調(diào)用Repository接口的方法來進(jìn)行分頁查詢:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

@Service
public class UserService {

    @Autowired
    private UserRepository userRepository;

    public Page<User> findAllUsers(int pageNo, int pageSize) {
        Pageable pageable = PageRequest.of(pageNo, pageSize);
        return userRepository.findAll(pageable);
    }
}

最后,在Controller層中接收請求參數(shù),并調(diào)用Service層方法來實(shí)現(xiàn)分頁查詢:

import org.springframework.beans.factory.annotation.Autowired;
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 {

    @Autowired
    private UserService userService;

    @GetMapping("/users")
    public Page<User> getUsers(@RequestParam int pageNo, @RequestParam int pageSize) {
        return userService.findAllUsers(pageNo, pageSize);
    }
}

這樣就可以在JPA中實(shí)現(xiàn)MySQL的分頁查詢了。當(dāng)調(diào)用/users接口時(shí),可以傳入pageNopageSize參數(shù)來獲取指定頁數(shù)的數(shù)據(jù)。

0