Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JPQL limit query [duplicate]

How can I limit in a select query of JPQL named query? I need the limit to be done in the query level itself and not in the java layer!!! I am trying to use

@NamedQueries(value = {         @NamedQuery(name = UserNotification.QueryName.NOTIFICATION_DISPLAYED,                     query = "SELECT un FROM UserNotification un " +                             "WHERE un.orgId IN (:orgList) " +                             "AND un.user.id = :userId LIMIT 5") 

but in vain!!!

Please suggest

like image 950
user3115056 Avatar asked Dec 19 '13 10:12

user3115056


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.

Is JPQL simpler than SQL?

JPQL syntax is very similar to the syntax of SQL. Having SQL like syntax is an advantage because SQL is a simple structured query language and many developers are using it in applications. SQL works directly against relational database tables, records and fields, whereas JPQL works with Java classes and instances.

Does JPQL support the limit keyword for pagination?

JPQL doesn't support the LIMIT keyword.


1 Answers

JPQL does not provide a mechanism to limit queries. This is most often achieved by using the setMaxResults() method on the Query. If you must avoid specifying this in Java code, you could make a view in the database that contains your query and performs the limit. Then map an entity to this view as you would a table.

Example:

List<String> resultList= query.setMaxResults(100).getResultList(); 
like image 76
Kevin Bowersox Avatar answered Dec 01 '22 18:12

Kevin Bowersox