The Wild

How to Limit Hibernate Query Results

· 4 min read · Mammals

In this article
  1. Why Limiting Results Matters
  2. Using setMaxResults()
  3. Using LIMIT in JPQL
  4. Pagination with setFirstResult() and setMaxResults()
  5. Differences Across Databases
  6. Common Pitfalls and Solutions
  7. Alternatives to setMaxResults()
  8. Frequently Asked Questions

To limit Hibernate query results, use the setMaxResults() method on a Query or TypedQuery object, or use the LIMIT clause in JPQL (e.g., query.setMaxResults(10)). This method translates to the database's native LIMIT or TOP syntax, effectively restricting the number of returned rows.

Why Limiting Results Matters

Fetching more data than needed wastes memory and bandwidth, slows down your application, and can cause out-of-memory errors when dealing with large tables. Limiting results is essential for pagination, displaying only the first few items, or implementing “load more” features. Hibernate provides a clean, database-agnostic way to do this without writing native SQL.

Using setMaxResults()

The most common approach is calling setMaxResults(int maxResults) on a query before executing it. Here’s a concrete example:

TypedQuery<User> query = entityManager.createQuery("SELECT u FROM User u", User.class);
query.setMaxResults(10);
List<User> users = query.getResultList();

This works for HQL, JPQL, and Criteria API queries. For native SQL queries, you can use createNativeQuery() and still call setMaxResults().

Using LIMIT in JPQL

JPQL (Java Persistence Query Language) does not have a standard LIMIT clause, but Hibernate allows you to add it as a hint or use it directly in some versions. The recommended way is still setMaxResults(), because it’s portable across JPA providers. However, if you’re using Hibernate-specific APIs, you can write:

Query query = session.createQuery("FROM User");
query.setMaxResults(10);

Some developers mistakenly try LIMIT 10 in JPQL—this will cause a parsing error in standard JPA. Stick to setMaxResults().

Pagination with setFirstResult() and setMaxResults()

For pagination, combine setMaxResults() with setFirstResult(int startPosition). For example, to get page 3 with 20 items per page:

  1. Calculate offset: (pageNumber - 1) * pageSize → (3-1)*20 = 40.
  2. Set first result: query.setFirstResult(40).
  3. Set max results: query.setMaxResults(20).

This generates SQL like LIMIT 20 OFFSET 40 in PostgreSQL or MySQL, or OFFSET 40 ROWS FETCH NEXT 20 ROWS ONLY in SQL Server.

Differences Across Databases

Hibernate translates setMaxResults() to the appropriate dialect:

  • MySQL/PostgreSQL: LIMIT n
  • Oracle: FETCH FIRST n ROWS ONLY (or older ROWNUM handling)
  • SQL Server: TOP n or OFFSET ... FETCH
  • H2: LIMIT n

This portability is a key advantage—you don’t rewrite queries when switching databases.

Common Pitfalls and Solutions

One common mistake is forgetting that setMaxResults() applies to the number of rows returned, not the number of entities if you have joins with collections. For example, if a User has many Orders and you query SELECT DISTINCT u FROM User u JOIN u.orders, setting max results to 10 might return fewer than 10 users because the SQL limits the joined rows. To avoid this, use DISTINCT or a subquery.

Another issue is that setMaxResults() with setFirstResult() can be inefficient for large offsets because the database still scans all rows before the offset. For very large datasets, consider keyset pagination (using WHERE id > lastId) instead.

Finally, always close your query or entity manager properly to avoid resource leaks—this is unrelated to limiting but often forgotten.

Alternatives to setMaxResults()

If you’re using Spring Data JPA, you can use Pageable objects in repository methods:

Page<User> page = userRepository.findAll(PageRequest.of(0, 10));

This internally uses setMaxResults() and setFirstResult(). Another alternative is the @QueryHints annotation with org.hibernate.fetchSize, but that hints at the JDBC fetch size, not the result limit.

Frequently Asked Questions

Can I use LIMIT in HQL?

No, standard HQL/JPQL does not support LIMIT. Use setMaxResults() instead. Hibernate will generate the correct SQL for your database.

Does setMaxResults() work with native queries?

Yes, you can call setMaxResults() on a native SQL query created via createNativeQuery(). It will append the appropriate limit clause to your SQL.

What if I need to limit results but also count total records?

You need two separate queries: one for the count (e.g., SELECT COUNT(u) FROM User u) and one for the page data with setMaxResults() and setFirstResult(). There is no built-in way to get both in one query.

Is setMaxResults() safe against SQL injection?

Yes, because it’s a parameterized method—Hibernate binds the integer value as a parameter, not as a string concatenation. Always use the method instead of concatenating values into your query string.

Why does my query return fewer results than setMaxResults()?

This can happen if you have duplicate rows due to joins, or if you use DISTINCT and the database applies the limit before eliminating duplicates. Use a subquery or fetch joins carefully to get the expected count.