SpringBoot整合JPA的分页查询可以通过使用Spring Data JPA提供的Pageable接口来实现。首先,需要在Repository接口中定义一个方法,方法的返回类型为Page<T>,其中T为查询的实体类,方法的参数中可以传入一个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中定义的方法,并传入一个PageRequest对象来指定分页的参数,例如:
import org.springframework.beans.factory.annotation.Autowired;import org.springframework.data.domain.Page;import org.springframework.data.domain.PageRequest;import org.springframework.stereotype.Service;@Servicepublic class UserService { @Autowired private UserRepository userRepository; public Page<User> getUsers(int page, int size) { PageRequest pageable = PageRequest.of(page, size); return userRepository.findAll(pageable); }}最后,在Controller层中调用Service中定义的方法并返回分页查询的结果,例如:
import org.springframework.beans.factory.annotation.Autowired;import org.springframework.data.domain.Page;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RequestParam;import org.springframework.web.bind.annotation.RestController;@RestControllerpublic class UserController { @Autowired private UserService userService; @GetMapping("/users") public Page<User> getUsers(@RequestParam(defaultValue = "0") int page, @RequestParam(defaultValue = "10") int size) { return userService.getUsers(page, size); }}通过以上步骤,就可以实现SpringBoot整合JPA的分页查询功能。在前端调用接口时,可以传入page和size参数来控制分页查询的页数和每页数据量。


