使用@RestController 在 Spring 中分页,但不使用 Spring Data Rest Pageable?
Pagination in Spring using @RestController, but without using Spring Data Rest Pageable?
我知道使用 Spring Data Rest 我可以像这样使用分页的内置功能
Page<Product> findByCategoryId(@RequestParam("id") Long id, Pageable pageable);
但是,我在项目中使用 Spring mvc @RestController 并希望实现相同的功能
我试过这样:-
Session currentSession = entityManager.unwrap(Session.class);
Query<Product> theQuery = currentSession.createQuery("from Product", Product.class);
theQuery.setFirstResult((pageNumber-1) * pageSize); // This is 0 based
theQuery.setMaxResults(pageSize);
List<Product> dataList = theQuery.getResultList();
return dataList;
它有效,但我没有在 table 中得到 记录总数 的 count。
对于 UI 分页,我需要它。
所以我每次都必须像上面那样先打 2 个查询,然后再打 1 个查询来获取记录大小。 (如果更新记录可能会导致数据同步问题)
或
在SINGLE QUERY
中有没有更好的方法来实现这个
如果您需要记录总数,则必须创建第二个查询。
您可以在一个带有子查询的查询中执行此操作,但您不能将实体用作 return 类型。
关于数据同步问题:如果您运行在同一事务中进行两个查询,则没有问题。
顺便说一句。为什么要打开 Hiberante Session?在您的示例中不需要这样做。
我知道使用 Spring Data Rest 我可以像这样使用分页的内置功能
Page<Product> findByCategoryId(@RequestParam("id") Long id, Pageable pageable);
但是,我在项目中使用 Spring mvc @RestController 并希望实现相同的功能 我试过这样:-
Session currentSession = entityManager.unwrap(Session.class);
Query<Product> theQuery = currentSession.createQuery("from Product", Product.class);
theQuery.setFirstResult((pageNumber-1) * pageSize); // This is 0 based
theQuery.setMaxResults(pageSize);
List<Product> dataList = theQuery.getResultList();
return dataList;
它有效,但我没有在 table 中得到 记录总数 的 count。 对于 UI 分页,我需要它。
所以我每次都必须像上面那样先打 2 个查询,然后再打 1 个查询来获取记录大小。 (如果更新记录可能会导致数据同步问题)
或
在SINGLE QUERY
中有没有更好的方法来实现这个如果您需要记录总数,则必须创建第二个查询。
您可以在一个带有子查询的查询中执行此操作,但您不能将实体用作 return 类型。
关于数据同步问题:如果您运行在同一事务中进行两个查询,则没有问题。
顺便说一句。为什么要打开 Hiberante Session?在您的示例中不需要这样做。