java - 如何获取 JPA 自定义查询的结果作为页面

标签 java spring jpa orm pagination

我有一个存储库,它返回 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/

相关文章:

spring - 为什么没有像 RestTemplate 中的 postForEntity 那样的 patchForEntity 方法?

java - 使用 spring-hibernate 的 2 个不同的数据库连接

java - Gradle 构建因从服务器 : Proxy Authentication Required, 接收到状态代码 407 而失败,但具有类似 deps 的另一个项目成功

java - 如何将 JPA 元组结果投影到实体中

java - Hibernate JPA 和 Spring javax.persistence.TransactionRequiredException : no transaction is in progress (2)

java - 无法使用@MapsId 和@Id 进行查询,但仅适用于@Id

java - 如何缩短JSP中的数字?

java - 在同步中使用本质锁

java - GWT/GPE/App Engine : How to (intelligently) find missing . jar 并将它们复制到/WEB-INF/lib 吗?

java - 在异步调用中更改变量