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?
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.
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.
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.
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()
You can work it out with Query setFirstResult and setMaxResult
methods
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With