【发布时间】:2020-11-14 02:17:15
【问题描述】:
我有一个存储库,它返回 Page<Mind>:
public interface MindRepository extends PagingAndSortingRepository<Mind, Integer> {
Page<Mind> findByCountry(String country, Pageable pageable);
}
还有一个使用它的控制器:
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);
}
一切正常。控制器以适合 FrontEnd 的 json 格式返回 Page<Mind>。
但现在我必须使查询更复杂,有几个过滤器,动态变化。我想像这样使用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 :(
最好的解决方法是什么?
【问题讨论】:
-
你试过link吗?
-
@ruba 谢谢!它必须工作。但由于某些原因,原生 SQL 现在更适合我,所以我正在尝试 Kavithakaran 方式。
-
如果您启用 Spring data web 支持扩展和 QueryDSL 扩展,您将获得所有这些(即排序、过滤(按动态标准)和页面),而无需编写任何代码。 stackoverflow.com/questions/59027999/…
标签: java spring jpa orm pagination