Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to write order by and limit query in jpa [duplicate]

Possible Duplicate:
Select top 1 result using JPA

i wish to fetch top 10 results based on 'totalTradedVolume' filed of my table 'MasterScrip' when i write the following query:

Collection<MasterScrip> sm=null;
   sm=em.createQuery("select m from MasterScrip m where m.type = :type order by m.totalTradedVolume limit 2").setParameter("type", type).getResultList();

i get the following exception :

Caused by: java.lang.IllegalArgumentException: An exception occurred while creating a query in EntityManager: 
Exception Description: Syntax error parsing the query [select m from MasterScrip m where m.type = :type order by m.totalTradedVolume limit 2], line 1, column 78: unexpected token [limit].
Internal Exception: NoViableAltException(80@[])

something's wrong with my jpa query. can anyone pls correct me?

like image 596
z22 Avatar asked May 23 '12 18:05

z22


People also ask

How do I limit a JPA query?

Limiting query results in JPA is slightly different to SQL; we don't include the limit keyword directly into our JPQL. Instead, we just make a single method call to Query#maxResults, or include the keyword first or top in our Spring Data JPA method name. As always, the code is available over on GitHub.

What are three methods to execute queries in JPA?

There are three basic types of JPA Queries:Query, written in Java Persistence Query Language (JPQL) syntax. NativeQuery, written in plain SQL syntax. Criteria API Query, constructed programmatically via different methods.

How can I apply pagination in JPA?

Once we have our repository extending from PagingAndSortingRepository, we just need to: Create or obtain a PageRequest object, which is an implementation of the Pageable interface. Pass the PageRequest object as an argument to the repository method we intend to use.


2 Answers

limit is not recognized in JPA. You can instead use the query.setMaxResults method:

sm = em.createQuery("select m from MasterScrip m where m.type = :type 
        order by m.totalTradedVolume")
    .setParameter("type", type)
    .setMaxResults(2).getResultList()
like image 161
Hari Menon Avatar answered Oct 10 '22 16:10

Hari Menon


You can work it out with Query setFirstResult and setMaxResult methods

like image 28
RP- Avatar answered Oct 10 '22 14:10

RP-