JPQL limit query

user3115056 picture user3115056 · Dec 19, 2013 · Viewed 70.8k times · Source

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

Answer

Kevin Bowersox picture Kevin Bowersox · Dec 19, 2013

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();