我到处搜索同时使用这 3 个 JPA 概念的 Spring 代码示例,这在查询时非常重要:
过滤-使用
Example,ExampleMatcher分页 - 使用
Pageable(或类似的)排序 - 使用
Sort
到目前为止,我只看到同时使用其中 2 个的示例,但我需要一次使用所有这些示例。你能给我看一个这样的例子吗?
谢谢你。
PS:这有过滤的例子Paging,Sorting但没有过滤。
这是一个示例,搜索标题属性的新闻,带有分页和排序:
实体 :
@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());
}
经过更多研究,最终找到了答案:
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);
}