我有一个存储库,它返回 Page<Mind>
:
public interface MindRepository extends PagingAndSortingRepository<Mind, Integer> {
Page<Mind> findByCountry(String country, Pageable pageable);
}
以及使用它的 Controller :
private MindRepository mindRepository;
@GetMapping(path = "/minds", produces = "application/json")
public Page<Mind> getMinds(String country, Integer page, Integer size) {
Pageable pageable = PageRequest.of(page,size);
return mindRepository.findByCountry(country,pageable);
}
一切都很好。 Controller 返回Page<Mind>
在适合前端的 json 中。
但现在我必须使查询更加复杂,使用多个过滤器,动态更改。我想使用createQuery
像这样:
public interface CustomizedMindRepository<T> {
Page<T> findByCountry(String country, Pageable pageable);
}
public interface MindRepository extends PagingAndSortingRepository<Mind, Integer>,CustomizedMindRepository {
Page<Mind> findByCountry(String country, Pageable pageable);
}
public class CustomizedMindRepositoryImpl implements CustomizedMindRepository {
@PersistenceContext
private EntityManager em;
@Override
public Page<Mind> findByCountry(String country, Pageable pageable) {
return em.createQuery("from minds where <dynamical filter> AND <another dynamical filter> AND <...etc>", Mind.class)
.getResultList();
}
}
但是getResultList()
返回List
,不是Page
:(
解决这个问题的最佳方法是什么?
最佳答案
- 页面存储库调用执行两个调用,一个用于获取结果,另一个用于获取总大小。因此,您还必须通过执行计数查询来复制该行为
@Override
public Page<Mind> findByCountry(String country, Pageable pageable) {
long offset = pageable.getPageNumber() * pageable.getPageSize();
long limit = pageable.getPageSize();
List<Item> itemsInNextPage = em.createQuery(query)
.setFirstResult(offset)
.setMaxResults(limit)
.getResultList();
long total = // Another query to get the total count
List<Mind> results = em.createQuery("from minds ...", Mind.class)
.getResultList();
return new PageImpl(results, pageable, total);
}
关于java - 如何获取 JPA 自定义查询的结果作为页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63069770/