Pagination in createNativeQuery

时间:2017-10-12 09:48:19

标签: java mysql spring jpa spring-boot

I want to implement Pageable in my custom query.Below is the code I am using.The sql is dummy query.Could someone please tell me how can I calculate total rows,lastelement from following?

EntityManager em = OpenJPAUtils.openEntityManager();
String sql="select DISTINCT student.studentId from student where ... LIMIT  :limit OFFSET  :offSet ; "  
query = em.createNativeQuery(sql);
query.setParameter("limit", pageable.getPageSize());
query.setParameter("offSet", pageable.getPageNumber());
query.getResultList()

I want total counts but the limit I have used will only give that much only. I could use the same query without limit to count the total rows but the query is very big and I don't want to run the same query twice to get total counts and calculate the rows. I would really appreciate the help.

1 个答案:

答案 0 :(得分:3)

Why not use pagination provided by JPA?

query.setFirstResult(firstIndex);
query.setMaxResults(firstIndex + pageSize);

Then no need for LIMIT clause in sql:

String sql="select DISTINCT student.studentId from student where ..."