java - Spring Data JPA,如何通过Pageable获取最后一页

标签 java spring hibernate jpa

我想获取一个实体的最后 5 条记录。但无法通过 Spring Data JPA 获取。

最初我试图通过 LIMIT 查询获取数据,但 JPA 不支持 LIMIT。

后来我尝试了 Pageable 接口(interface)。

Pageable pageCount = new PageRequest(0, 10, Direction.ASC,"id");
List<TxnEntity> txnEntities = txnDAO
            .findByAccountEntity(accountEntity,pageCount);

这给了我 10 个对象的第一页。

但我的要求是获得最后 10 或 5 个对象。那么如何通过Spring框架中的Pageable接口(interface)获取呢?

最佳答案

来自引用文档:

To find out how many pages you get for a query entirely you have to trigger an additional count query. By default this query will be derived from the query you actually trigger.

您可以通过提前发出计数查询来确定页数:

Long count = txnDAO.countByAccountEntity(accountEntity);
Pageable pageCount = new PageRequest((int)count/10, 10, Direction.ASC,"id");

关于java - Spring Data JPA,如何通过Pageable获取最后一页,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30326361/

相关文章:

java - Spring Integration + 过滤器 + 向 REST Controller 发送 400 错误请求

java - Mockito when() 方法不起作用并出现空指针异常

java - Spring Data JPA 关系注释

java - Hibernate插入行外键错误

java - Gson.toString() 给出错误 "IllegalArgumentException: multiple JSON fields named mPaint"

java - 在 Eclipse 中运行 TestNG 单元测试会忽略最新更改

hibernate - 为什么需要传统的 Hibernate?

java - 注释 Propagation.NEVER 不起作用

java - 使用 fop 2.3 版本时找不到 FOP 图像

java - 确定 Java 应用程序使用的类