4

I am using the following code to execute an HQL query with Hibernate:

String myHqlQuery = "select from MyTable where Something = ? order by SomeVal";
// Set bind values ...
getHibernateTemplate().find(myHqlQuery, bindParams);

Now, I want to select the top N rows from the table. I know mySql has the LIMIT keyword which is not available in HQL. I also know that Hibernate has the setMaxResults() method you can run on a Query object.

My question is - is there any way to add the "limit" constraint without have to change my code too much (i.e. executing the query via a HibernateTemplate object)?

kli
  • 41
  • 1
  • 2
  • 1
    possible duplicate of [How do you do a limit query in HQL](http://stackoverflow.com/questions/1239723/how-do-you-do-a-limit-query-in-hql) – hvgotcodes Dec 12 '10 at 00:05
  • your right..thanks..this question can be closed then I guess..unless of course theres actually way to do this now directly with HQL. – kli Dec 12 '10 at 00:20

2 Answers2

3

The below code works for me

    HibernateTemplate ht = getHibernateTemplate();
    ht.setMaxResults(10);
    List<Object> obj= ht.findByNamedQueryAndNamedParam("namedQuery",
            new String[] { "parameter1" },
            new Object[] { parameter1 });

So I think you should be able to do:

String myHqlQuery = "select from MyTable where Something = ? order by SomeVal";

// Set bind values ...

HibernateTemplate ht = getHibernateTemplate();

ht.setMaxResults(10);

ht.find(myHqlQuery, bindParams);
andrewsi
  • 10,807
  • 132
  • 35
  • 51
amartell
  • 31
  • 2
0

use

org.springframework.data.domain.Pageable

int numberOfItems = 10;

Pageable pageableTop = new PageRequest(0, numberOfItems);
yourRepository.findYourEntity(pageableTop);
izy
  • 1,085
  • 14
  • 18