在JPA中實現MySQL的分頁查詢可以通過使用Spring Data JPA提供的Pageable
接口來實現。下面是一個簡單的示例代碼:
首先,在Repository接口中定義一個方法,使用Pageable
作為參數來實現分頁查詢:
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層中調用Repository接口的方法來進行分頁查詢:
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層中接收請求參數,并調用Service層方法來實現分頁查詢:
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中實現MySQL的分頁查詢了。當調用/users
接口時,可以傳入pageNo
和pageSize
參數來獲取指定頁數的數據。