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.
这样在Query
上定义setFirstResult()
和setMaxResults()
(offset = 0和limit = 10):
sessionFactory.getCurrentSession().createQuery(criteriaQuery).setFirstResult(0).setMaxResults(10).getResultList());
To paginate you just have to set the first and max (assuming you're passing in a Pageable Object:
criteria.setFirstResult(pageable.gotOffset());
criteria.setMaxResults(pageable.getPageSize());
Also, to limit, just call:
Criteria queryCriteria = session.createCriteria(MonthlySubscriber.class);
queryCriteria.setFirstResult(0);
queryCriteria.setMaxResults(1);
monthlySubscriberList = queryCriteria .list();
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.