Scrivio Interview library
ConceptIntermediate6 min read · updated 12 November 2026

Name useful JPA and Hibernate query hints and what each does: read-only, fetch size, timeout, lock timeout and comment.

org.hibernate.readOnly loads entities without snapshots so they skip dirty checking; org.hibernate.fetchSize sets the JDBC fetch size so large results are streamed in chunks; jakarta.persistence.query.timeout cancels a query after a number of milliseconds; jakarta.persistence.lock.timeout limits how long a pessimistic lock request waits; and org.hibernate.comment adds a SQL comment so we can tell which code sent a query. Hibernate 6 collects the names as constants in the HibernateHints and SpecHints classes.

Why this question is asked

Query hints are the small dials of JPA. Each one fixes a specific production problem: memory spent on entities we never change, an out-of-memory error while exporting a large table, a query that runs for ten minutes, a request stuck behind a row lock, or a slow query in the database log that nobody can trace back to its code. Interviewers ask for these five because together they show we have run JPA under load. In this answer, we will recap how hints are passed, then go through each hint with what it does underneath, and finish with a table and the constant classes that hold the names.

1A Quick Recap of How Hints Are Passed

A hint is a name and a value handed to the JPA provider with a query. Standard names start with jakarta.persistence and work with any provider; Hibernate's own start with org.hibernate. Unknown names are ignored, so a misspelled hint fails silently.

Java
List<Product> list = em.createQuery("select p from Product p", Product.class)
.setHint(HibernateHints.HINT_READ_ONLY, true) // "org.hibernate.readOnly"
.setHint(SpecHints.HINT_SPEC_QUERY_TIMEOUT, 2000) // "jakarta.persistence.query.timeout"
.getResultList();
// Spring Data: the same hints on a repository method
@QueryHints(@QueryHint(name = HibernateHints.HINT_FETCH_SIZE, value = "500"))
Stream<Product> streamAllBy();

The constant names in the code are those of Hibernate 6. HibernateHints is in org.hibernate.jpa and SpecHints holds the standard Jakarta names; check your version, since the older QueryHints class from Hibernate 5 is gone or deprecated.

2Read-Only: Skip the Snapshots

When Hibernate loads an entity normally, it keeps a copy of its loaded state, the snapshot, so that at flush time it can compare and find changes. org.hibernate.readOnly = true loads the query's entities in read-only mode. No snapshot is kept and those entities are left out of dirty checking. For a screen that loads 10,000 rows to display them, this roughly halves the memory used by the entities and removes the comparison work at every flush. Changes made to such entities are not written to the database.

3Fetch Size: Stream Large Results

The JDBC fetch size is how many rows the driver pulls from the database per round trip while we iterate a result. org.hibernate.fetchSize sets it for a query. The important catch is driver behaviour. The PostgreSQL driver by default reads the entire result into memory before returning the first row, and only uses a cursor with the fetch size when the connection is not in auto-commit mode, that is, inside a transaction. MySQL Connector/J also loads everything by default and needs useCursorFetch=true, or its special streaming mode, before a fetch size helps.

Java
@Transactional(readOnly = true) // PostgreSQL needs a transaction for cursors
public void export(Writer out) {
try (Stream<Product> s = repo.streamAllBy()) { // fetchSize 500 from the hint
s.forEach(p -> {
write(out, p);
em.detach(p); // keep the persistence context small
});
}
}
// memory stays flat: about 500 rows in the driver at a time

Notice the detach. Streaming helps the driver, but every loaded entity still sits in the persistence context until we detach it or clear the context, so a long export must do one or the other.

4Query Timeout and Lock Timeout

jakarta.persistence.query.timeout is in milliseconds. Hibernate passes it to JDBC Statement.setQueryTimeout, which counts whole seconds, and the driver cancels the statement on the server when time runs out. Spring translates the result into a QueryTimeoutException. It protects us from a query that runs too long because of a bad plan or a missing index.

jakarta.persistence.lock.timeout is different. It applies when the query asks for a pessimistic lock, for example with LockModeType.PESSIMISTIC_WRITE, which becomes select ... for update. It limits how long we wait for another transaction to release the row. A value of 0 means do not wait at all, and Hibernate renders nowait on databases that support it. How other values are applied differs between dialects, some use a wait clause and some a session setting such as PostgreSQL's lock_timeout, so check your version and database. Without a lock timeout, a request can wait as long as the other transaction holds the lock.

Java
Account a = em.find(Account.class, 7L, LockModeType.PESSIMISTIC_WRITE,
Map.of(SpecHints.HINT_SPEC_LOCK_TIMEOUT, 0));
// select ... from account where id = ? for update nowait
// if another transaction holds row 7: PessimisticLockException / LockTimeoutException at once

5Comment: Know Who Sent the Query

org.hibernate.comment adds a comment to the generated SQL, such as /* catalog search */. The value is that the comment shows up where database people look: the slow query log, pg_stat_activity, or a monitoring tool. When a DBA asks which service runs this awful query, the comment answers. Hibernate only writes comments when hibernate.use_sql_comments=true is set, so the hint does nothing without that property.

Java
@QueryHints(@QueryHint(name = HibernateHints.HINT_COMMENT, value = "catalog-service: search by category"))
@Query("select p from Product p where p.category = :c")
List<Product> search(@Param("c") String c);
// with hibernate.use_sql_comments=true:
// /* catalog-service: search by category */ select p1_0.id, ... from product p1_0 where p1_0.category=?
Five useful hints
Hint nameWhat it doesWatch out for
org.hibernate.readOnlyNo snapshots, no dirty checkingChanges are silently not saved
org.hibernate.fetchSizeRows per JDBC round tripPostgreSQL needs a transaction for cursors
jakarta.persistence.query.timeoutCancel after N millisecondsJDBC counts seconds; driver support
jakarta.persistence.lock.timeoutMax wait for a pessimistic lock0 means nowait; varies by dialect
org.hibernate.commentSQL comment for attributionNeeds hibernate.use_sql_comments=true

One warning: some statistics tools normalize queries by their text, so changing comments, for example by including a request id, can split one query into thousands of entries. A fixed comment per method is the safe choice.

6Follow-up questions

Where do I find the full list of hint names?

In Hibernate 6, the HibernateHints interface holds Hibernate's own hints and SpecHints holds the standard Jakarta Persistence ones, both in the org.hibernate.jpa package. AvailableHints combines them. Using these constants rather than strings is the simplest way to avoid silent typos.

Is the fetch size hint useful for small queries?

Not really. For a query returning 50 rows, the driver's default behaviour is fine. The fetch size matters when results are large enough that holding them all would use a lot of memory, such as exports, batch jobs and streams.

What is the difference between a query timeout and a transaction timeout?

A query timeout limits one statement. A transaction timeout, @Transactional(timeout = 5), limits the whole unit of work, and Spring applies the remaining time to each query it runs through JPA. Often we want both: a tight limit on a known heavy query and an overall limit on the transaction.

7Conclusion

In this answer, we went through five hints. org.hibernate.readOnly skips snapshots and dirty checking, org.hibernate.fetchSize controls how many rows the driver fetches per round trip for streaming, jakarta.persistence.query.timeout cancels a slow statement after a number of milliseconds, jakarta.persistence.lock.timeout bounds the wait for a pessimistic lock, and org.hibernate.comment tags the SQL so we can attribute it. Hibernate 6 lists their names in HibernateHints and SpecHints.

What to say in the interviewAbout 70 seconds aloud

Open with

There are five I use regularly. org.hibernate.readOnly tells Hibernate to load the entities without a snapshot, so they are not dirty checked at flush. That saves memory and CPU on big read queries, and any change to those entities is ignored. org.hibernate.fetchSize sets the JDBC fetch size, how many rows the driver pulls per round trip, which matters when streaming large results; on PostgreSQL it only uses a cursor inside a transaction, and on MySQL I need useCursorFetch. jakarta.persistence.query.timeout is a standard hint in milliseconds; Hibernate passes it to setQueryTimeout, and the driver cancels the statement when it expires. jakarta.persistence.lock.timeout is about pessimistic locks: how long select for update waits for another transaction; zero means nowait, and other values depend on the dialect. org.hibernate.comment adds a SQL comment so a DBA looking at the slow query log can see which code sent the query, but only when hibernate.use_sql_comments is on.

Then, if they want more

In Hibernate 6 I take the names from the HibernateHints and SpecHints constants rather than typing strings, because unknown hints are silently ignored.

About this answer

Last updated
12 November 2026
Versions it names
Hibernate 6, Hibernate 5
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Name useful JPA and Hibernate query hints and what each does: read-only, fetch size...": https://scrivio-interview-library.netlify.app/databases/jpa-queries/ad7b8438aa/