How to paginate a JPA Query

前端 未结 3 706
心在旅途
心在旅途 2021-01-30 11:52

I have a submission table with columns like ID, Name, Code among other properties. My requirement is to search for records based on the me

3条回答
  •  渐次进展
    2021-01-30 12:14

    You can use the JPA pagination for both entity queries and native SQL.

    To limit the underlying query ResultSet size, the JPA Query interface provides the setMaxResults method.

    Navigating the following page requires positioning the result set where the last page ended. For this purpose, the JPA Query interface provides the setFirstResult method.

    Using pagination with a JPQL query looks as follows:

    List posts = entityManager
    .createQuery(
        "select p " +
        "from Post p " +
        "order by p.createdOn ")
    .setFirstResult(10)
    .setMaxResults(10)
    .getResultList();
    

    Criteria API is just the same since you need to create a Query from the CriteriaQuery:

    CriteriaBuilder qb = em.getCriteriaBuilder();
    CriteriaQuery cq = qb.createQuery(Post.class);
    
    Root root = cq.from(Post.class);
    cq.orderBy(qb.asc(root.get("createdOn")));
    
    List posts = em
    .createQuery(cq)
    .setFirstResult(10)
    .setMaxResults(10)
    .getResultList();
    

提交回复
热议问题