Linux 拨号vps windows公众号手机端

springboot分页查询的方法有哪些

lewis 9年前 (2016-10-23) 阅读数 14 #程序编程
文章标签 springboot

在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分页查询方法,根据具体的业务需求和喜好可以选择适合的方法来实现分页查询。

版权声明

本文仅代表作者观点,不代表米安网络立场。

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

热门