Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set limit for a hibernate query

Tags:

hql

How can I set a limit to this hql query? When I add the limit keyword in the query, an error is thrown.

 @Query("from voucher v where  v.voucherType.typeDescription = :typeDescription and v.denomination = :denomination")
 public List<Voucher> findByVoucherTypeAndDenomination(@Param("typeDescription") String typeDescription,@Param("denomination") BigDecimal denomination);
like image 588
Samuel Anertey Avatar asked Jul 18 '13 23:07

Samuel Anertey


2 Answers

When you call your query add the following:

.setFirstResult(firstResult).setMaxResults(limit);

setFirstResult is the (optional) offset, setMaxResults is the limit.

UPDATE

Docs:
http://docs.jboss.org/hibernate/orm/3.6/javadocs/org/hibernate/Query.html#setMaxResults(int)

If you use entityManager, it can be like:

entityManager.createQuery("yourQuery").setFirstResult(0).setMaxResults(5);
like image 175
Alex Avatar answered Sep 21 '22 12:09

Alex


You can use two method of Query object.

setFirstResult() // offset

setMaxResults() // limit

but you can not use it in HQL because limit is database vendor dependent so hibernate doesn't allow it through hql query

like image 31
Ankit Katiyar Avatar answered Sep 21 '22 12:09

Ankit Katiyar