1. 首页
  2. 软件开发
  3. SpringData——JPA的分页和排序查询

SpringData——JPA的分页和排序查询

  • 发布于 2024-08-17
  • 1 次阅读

在JPA中,进行分页和排序查询是常见的需求。通过使用Spring Data JPA提供的PagingAndSortingRepository接口,可以轻松实现分页和排序功能。

代码如下:

假设有一个实体类Book:

@Entity
public class Book {
   
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    
    private String title;
    
    private String author;
    
}

创建一个BookRepository接口继承自PagingAndSortingRepository:

public interface BookRepository extends PagingAndSortingRepository<Book, Long> {
   
}

然后在服务类中进行分页和排序查询:

@Service
public class BookService {
   
    
    @Autowired
    private BookRepository bookRepository;
    
    public Page<Book> findAllBooks(int page, int size, String sortBy) {
   
        Pageable pageable = PageRequest.of(page, size, Sort.by(sortBy));
        return bookRepository.findAll(pageable);
    }
}

在上面的代码中,通过PageRequest.of方法创建一个Pageable对象,指定了要查询的页数、每页大小和排序规则。然后调用bookRepository的findAll方法,传入Pageable对象,即可实现分页和排序查询。

原文链接: https://blog.csdn.net/2401_82884096/article/details/138150191