Scrivio Interview library
CodingFoundations5 min read · updated 12 November 2026

How do you apply a read-only hint and a query timeout to a Spring Data JPA repository method?

We put @QueryHints on the repository method, next to its @Query or on a derived query: @QueryHint(name = "org.hibernate.readOnly", value = "true") and @QueryHint(name = "jakarta.persistence.query.timeout", value = "2000"). The read-only hint loads entities without dirty-checking snapshots, and the timeout cancels the query after about two seconds. A @Transactional(readOnly = true) service method gives similar savings for the whole transaction, and we should check that our JDBC driver really supports query timeouts.

Why this question is asked

Hints are small switches we can attach to a query to change how Hibernate or the database runs it. Read-only and timeout are the two most useful for everyday services: one saves memory and CPU on read paths, the other stops a slow query from holding a request thread and a connection forever. Interviewers ask this to check that we know the annotation syntax and also what each hint actually does underneath. In this answer, we will recap what a query hint is, apply both hints to a repository method, explain what each one changes, compare with a read-only transaction, and look at driver support for timeouts.

1A Quick Recap of Query Hints

A query hint is a name-value pair passed to the JPA provider with a query. The JPA specification defines a few standard names, such as jakarta.persistence.query.timeout, and providers add their own, such as Hibernate's org.hibernate.readOnly. A provider ignores hints it does not recognize, which makes hints safe to add and also easy to misspell without noticing.

In plain JPA we pass them with query.setHint(name, value). In Spring Data JPA we declare them with @QueryHints on the repository method, and Spring Data applies them every time the method runs.

2Applying Both Hints to a Repository Method

The annotation goes on the method, together with its @Query, or on a derived query method that has no @Query at all.

Java
public interface ProductRepository extends JpaRepository<Product, Long> {
@QueryHints({
@QueryHint(name = "org.hibernate.readOnly", value = "true"),
@QueryHint(name = "jakarta.persistence.query.timeout", value = "2000") // milliseconds
})
@Query("select p from Product p where p.category = :category")
List<Product> findForCatalog(@Param("category") String category);
@QueryHints(@QueryHint(name = "jakarta.persistence.query.timeout", value = "500"))
List<Product> findBySku(String sku); // derived query with a hint
}

Notice the values are strings, because annotation attributes must be constants. Hibernate converts them. Instead of typing the names, we can use the constants in Hibernate's HibernateHints and SpecHints classes, for example HibernateHints.HINT_READ_ONLY, so a typo becomes a compile error.

3What the Read-Only Hint Changes

Normally, when Hibernate loads an entity, it also keeps a snapshot, a copy of the loaded values. At flush it compares each entity with its snapshot to find changes, which is dirty checking. For a page that loads 5,000 products only to display them, the snapshots double the memory and the comparison costs CPU at every flush, for nothing.

With org.hibernate.readOnly = true, the entities from that query are loaded in read-only mode: no snapshot is kept and Hibernate skips them during dirty checking. If code changes such an entity by mistake, the change is simply not written.

Java
@Transactional
public void readOnlyDemo() {
Product p = repo.findForCatalog("books").get(0); // loaded read-only
p.setPrice(new BigDecimal("1.00")); // changes the Java object only
} // commit: no update is sent
Effect of the two hints
HintWithout itWith it
org.hibernate.readOnly = trueSnapshot per entity, dirty checked at flushNo snapshot, no dirty check, changes ignored
jakarta.persistence.query.timeout = 2000Query may run for minutesCancelled after about 2 s, exception thrown

4What the Timeout Hint Changes

The timeout hint is in milliseconds. Hibernate passes it to JDBC with Statement.setQueryTimeout, which takes whole seconds, so 2000 becomes 2 seconds and values below a second are rounded, check your version for the exact rounding. When the time runs out, the driver asks the database to cancel the statement, and Hibernate throws an exception that Spring translates, typically into a QueryTimeoutException.

So a slow catalog query now fails fast with an error we can handle, for example by showing a friendly message, instead of holding a request thread and a pooled connection until a load balancer gives up.

5A Read-Only Transaction as the Alternative

@Transactional(readOnly = true) on a service method gives similar savings at the level of the whole transaction. With Hibernate, Spring sets the session to read-only by default, so every entity loaded in the transaction skips snapshots, and it sets the flush mode to manual so nothing is flushed. It also marks the JDBC connection read-only, which some setups use to route the transaction to a replica.

The two approaches combine well. The transaction-level setting covers whole read-only use cases, and the hint covers one heavy read inside a transaction that also writes. For timeouts, @Transactional(timeout = 5) also applies the remaining transaction time to each query Spring runs through JPA, which is a useful upper bound for the whole unit of work.

6Check That the Driver Supports Timeouts

A timeout hint is only as good as the JDBC driver. The PostgreSQL and MySQL drivers implement setQueryTimeout by sending a cancel request to the server. Some drivers, or some proxies and poolers in between, ignore or weaken it. So we test it: run a query that sleeps longer than the timeout, such as select pg_sleep(5) in PostgreSQL, through the repository and assert that the exception arrives after about two seconds. As a backstop that does not depend on the driver, the database itself can enforce a limit, such as PostgreSQL's statement_timeout for the service's user.

7Follow-up questions

Does the read-only hint make the database transaction read-only?

No. It only changes how Hibernate treats the loaded entities. The SQL and the transaction are the same. A read-only transaction, by contrast, marks the connection read-only too, and PostgreSQL then rejects writes in it.

What happens if we misspell a hint name?

Hibernate ignores unknown hints, usually without an error, so the query runs without the behaviour we wanted. Using the constants from HibernateHints and SpecHints avoids this, and a test that checks the behaviour, such as the timeout firing, catches it.

Can we set a default timeout for all queries?

Yes. A transaction timeout covers all queries in the transaction, and a database-side limit such as statement_timeout per user covers everything that service runs. The hint is then for queries that need a tighter limit than the default.

8Conclusion

In this answer, we applied @QueryHints to a Spring Data repository method with org.hibernate.readOnly, which loads entities without snapshots so they are not dirty checked, and jakarta.persistence.query.timeout, which cancels the query after the given milliseconds. We compared the hint with @Transactional(readOnly = true), which gives similar savings for a whole transaction, and saw why the driver's timeout support must be tested, with a database-side timeout as a backstop.

What to say in the interviewAbout 70 seconds aloud

Open with

I annotate the repository method with @QueryHints, either next to its @Query or on a derived query. Inside it I put two @QueryHint entries: org.hibernate.readOnly with value true, and jakarta.persistence.query.timeout with value 2000, which is in milliseconds.

Then, if they want more

I prefer the constants from HibernateHints and SpecHints so a typo does not silently disable the hint, because Hibernate ignores names it does not know. The read-only hint means Hibernate loads those entities without keeping a snapshot for dirty checking, so a big read uses less memory and flush is cheaper, and accidental changes to those entities are not written.

The timeout is passed to JDBC's setQueryTimeout, which works in seconds, and when it expires the driver cancels the statement and Spring throws a QueryTimeoutException that I can handle. If the whole use case only reads, I would rather put @Transactional(readOnly = true) on the service method, which with Hibernate makes the whole session read-only and skips flushing.

Finally I check the driver really supports query timeouts, with a test running pg_sleep longer than the limit, and I keep a database statement_timeout as a backstop.

About this answer

Last updated
12 November 2026
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 "How do you apply a read-only hint and a query timeout to a Spring Data JPA repository...": https://scrivio-interview-library.netlify.app/databases/jpa-queries/3458dfcbbc/