9

I am working on a project which uses Java,MySql,Struts2 MVC and Hibernate. I tried using limit statement in hql query but its not working properly.

Select t from table1 t where t.column1 = :someVal limit 0,5

EDIT: I am using this as a namedQuery and calling this namedQuery using JPA Template

This works correctly in MySql but when I ran this as a hql query this returns all records without regard to limit statement. Has anyone faced the same problem?? Any help appreciated!!

Regards, RDJ

4 Answers 4

5

Use hibernates functions for paging! setFirstResult(), setMaxResults()

http://www.javalobby.org/java/forums/t63849.html

0
1

use Query.setMaxResults(..)

2
  • I am using NamedQuery . Can the functions setFirstResult() and setMaxResults() work with namedQuery??
    – Richie
    Nov 26, 2009 at 7:18
  • 2
    Why don't you try reading the javadoc, or open the auto-complete in your IDE and see?
    – Bozho
    Nov 26, 2009 at 7:30
0

I think, If we use Criteria we can specify

Crietria c=session.createCriteria(Emp.class);
c.setFirstResult(0);
c.setMaxResult(5);
List list=c.list();

Here 0 and 5 works as limit 0,5

Source : http://www.javatpoint.com/hcql

-1
    List<Employee> dataList = null;
    Query hQuery = null;

    try {
        // Getting Session

        hSession = HibernateSessionFactory.getSession();
        hTransaction = hSession.beginTransaction();
        hQuery = hSession.getNamedQuery(query);

                    Iterator<Object> hIterator = paramMap.entrySet().iterator();

                    while (hIterator.hasNext()) {

     Map.Entry<String, Object> paramPair = (Map.Entry<String,Object>) hIterator.next();    

 hQuery.setParameter(paramPair.getKey(), paramPair.getValue());

        }

        hQuery.setFirstResult(1);
        hQuery.setMaxResults(100);

        System.out.println(hQuery);
        dataList = hQuery.list();

        hTransaction.commit();

    } catch (Exception e) {
        hTransaction.rollback();


    } finally {
        try {
            hSession.flush();
            HibernateSessionFactory.closeSession();
        } catch (Exception hExp) {}
2
  • 1
    This is just a bunch of code. Some explanation as to how this helps the OP's concrete issue would be nice
    – kolossus
    Oct 11, 2012 at 6:57
  • 1
    you can find two methods setFirstResult(),setMaxResults() in Query interface which help to get the record in pagination.. Jul 18, 2013 at 9:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.