jpa 2 hibernate limit (max results) to a CriteriaQ

2020-02-11 01:20发布

问题:

maybe it's a silly question but I cannot find the answer in the docs: How can set a limit to the CriteriaQuery using JPA2?

Thanks

回答1:

A CriteriaQuery is not an executable Query. You need to create a TypedQuery first using EntityManager.createQuery(criteriaQuery). You can then set the max results of this and execute it.



回答2:

You could define the offset/limit like this:

return em.createQuery(query)
     .setFirstResult(offset) // offset
     .setMaxResults(limit) // limit
     .getResultList();


回答3:

I usually use:

em.createQuery(criteria).setFirstResult(offset).setMaxResults(max).getResultList();