springboot分页查询的方法有哪些

2024-03-13

在Spring Boot中,可以使用以下方法来实现分页查询:

  1. 使用Spring Data JPA的Pageable接口和Page对象来实现分页查询。在Repository方法中,可以定义一个带有Pageable参数的查询方法,并返回Page对象。
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或Controller中,可以通过调用Repository的查询方法来进行分页查询,并获取到分页结果:

import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;

@Service
public class UserService {

    @Autowired
    private UserRepository userRepository;

    public Page<User> findAllUsers(int page, int size) {
        PageRequest pageable = PageRequest.of(page, size);
        return userRepository.findAll(pageable);
    }
}
  1. 使用Spring Data JPA的@Query注解和JPQL语句来实现分页查询。可以在Repository接口中定义带有@Query注解的查询方法,并在JPQL语句中使用LIMITOFFSET来限制查询结果的数量和偏移量。
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;

public interface UserRepository extends JpaRepository<User, Long> {

    @Query("SELECT u FROM User u")
    Page<User> findAllUsers(Pageable pageable);
}

在Service或Controller中,同样可以通过调用Repository的查询方法来进行分页查询,并获取到分页结果。

以上是两种常用的Spring Boot分页查询方法,根据具体的业务需求和喜好可以选择适合的方法来实现分页查询。

《springboot分页查询的方法有哪些.doc》

下载本文的Word格式文档,以方便收藏与打印。