Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to limit the results when using CriteriaQuery

I have inherited a groovy code base (that among other things) uses Hibernate as an ORM as part of Dropwizard and I've in the process of updating the dependencies I start seeing the following warnings.

org.hibernate.orm.deprecation: HHH90000022: Hibernate's legacy org.hibernate.Criteria API is deprecated; use the JPA javax.persistence.criteria.CriteriaQuery instead

As an experiment I tried updating one of the queries to use the new CriteriaQuery API. However pretty quickly I ran into an issue, the old code uses setMaxResults(). I assume under the hood this is using the LIMIT to limit the number of results.

How to I limit the results of a CriteriaQuery to 1?

A related question, how do I do pagination with CriteriaQuery?

I tried reading through the Hibernate 5.3 users guide, (especially chapter 16 the the new API) searing for "limits" and "max results" and such and all the talk I could find was in the "Legacy Hibernate Criteria Queries".

I'd be happy to provide some example code if it helps, but you could just use the example from the manual (Example 534. Selecting an attribute) and show how to enhance it by limiting the results.

like image 345
Jachin Avatar asked Dec 01 '25 05:12

Jachin


1 Answers

Define setFirstResult() and setMaxResults() on the Query like this (offset=0 and limit=10):

sessionFactory.getCurrentSession().createQuery(criteriaQuery).setFirstResult(0).setMaxResults(10).getResultList());
like image 182
Payam Soudachi Avatar answered Dec 04 '25 03:12

Payam Soudachi