4
votes

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)?

2
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

2 Answers

3
votes

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);
0
votes

use

org.springframework.data.domain.Pageable

int numberOfItems = 10;

Pageable pageableTop = new PageRequest(0, numberOfItems);
yourRepository.findYourEntity(pageableTop);