spring使用pageable、example和sort访问jpa存储库的示例

pzfprimi  于 2021-06-30  发布在  Java
关注(0)|答案(2)|浏览(267)

我到处搜索一段同时使用这3个jpa概念的spring代码示例,这在查询时非常重要:
过滤-使用 Example , ExampleMatcher 寻呼-使用 Pageable (或类似)
排序-使用 Sort 到目前为止,我只看到了同时使用其中两个的例子,但我需要同时使用所有的例子。你能给我举个例子吗?
谢谢您。
附言:这有一些例子 Paging 以及 Sorting 但不是过滤。

bwntbbo3

bwntbbo31#

经过更多的研究,最终找到了答案:

public Page<MyEntity> findAll(MyEntity entityFilter, int pageSize, 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, pageSize, sort); 
    return repository.findAll(filter, pageable);
}
jdgnovmf

jdgnovmf2#

下面是一个示例,通过分页和排序在标题属性上搜索新闻:
实体:

@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", 0, 10, "title", "asc")) {
    log.info(news.getTitle());
}

相关问题