简体   繁体   中英

Pagination in createNativeQuery

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.

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 ..."  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM