![](/img/trans.png)
[英]Spring Boot repository with Example, Specification and Pageable together
[英]Example of spring using Pageable, Example and Sort accessing a JPA repository
我到处搜索 Spring 代码段的示例,同时使用这 3 个 JPA 概念,在查询时非常重要:
过滤 - 使用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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.