spring 使用 Pageable、Example 和 Sort 访问 JPA 存储库的示例

问题描述

我到处搜索同时这三个 JPA 概念的 Spring 代码示例,这在查询时非常重要:

  • 过滤 - 使用 Example,ExampleMatcher

  • 分页 - 使用 Pageable(或类似的)

  • 排序 - 使用 Sort

到目前为止,我只看到了同时使用其中 2 个的示例,但我需要一次使用所有这些。你能给我举个例子吗?

谢谢。

PS:ThisPagingSorting 的示例,但没有过滤。

解决方法

这里是一个例子,搜索标题属性的新闻,分页和排序:

实体:

@Getter
@Setter
@Entity
public class News {

    @Id
    private Long id;

    @Column
    private String title;

    @Column
    private String content;

}

存储库:

public interface NewsRepository extends JpaRepository<News,Long> {

}

服务

@Service
public class NewsService {

    @Autowired
    private NewsRepository newsRepository;

    public Iterable<News> getNewsFilteredPaginated(String text,int pageNumber,int pageSize,String sortBy,String sortDirection) {

        final News news = new News();
        news.setTitle(text);

        final ExampleMatcher matcher = ExampleMatcher.matching()
                .withIgnoreCase()
                .withIgnorePaths("content")
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING);

        return newsRepository.findAll(Example.of(news,matcher),PageRequest.of(pageNumber,pageSize,sortDirection.equalsIgnoreCase("asc") ? Sort.by(sortBy).ascending() : Sort.by(sortBy).descending()));

    }
}

调用示例:

for (News news : newsService.getNewsFilteredPaginated("hello",10,"title","asc")) {
    log.info(news.getTitle());
}
,

经过反复研究,最终找到了答案:

public Page<MyEntity> findAll(MyEntity entityFilter,int currentPage){
    ExampleMatcher matcher = ExampleMatcher.matchingAll()
        .withMatcher("name",exact()); //add filters for other columns here
    Example<MyEntity> filter = Example.of(entityFilter,matcher); 
    Sort sort = Sort.by(Sort.Direction.ASC,"id"); //add other sort columns here
    Pageable pageable = PageRequest.of(currentPage,sort); 
    return repository.findAll(filter,pageable);
}

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...