Sub topic 9
Custom queries with @Query
Prerequisites
This chapter assumes you know the following:
- You can write derived query methods such as
findByTitleContainingIgnoreCase. - You know the
AuthorandBookentities from earlier chapters, whereBookowns theauthor_idforeign key. - You can read basic SQL and JPQL-style
select ... from ... wherestatements.
Why derived queries are not enough
Derived query methods work well for simple filters. Their names grow unwieldy once you add joins, several conditions or aggregates. A method called findByAuthorNameAndPublishedYearGreaterThanEqualOrderByTitleAsc is hard to read and hard to change.
The @Query annotation lets you write the query yourself and name the method anything you like. Spring Data validates JPQL queries when the application starts, so many mistakes show up at boot time and not at runtime.
JPQL basics
JPQL (Jakarta Persistence Query Language) looks like SQL, but it works on entities and their attributes, not on tables and columns. Names are the Java class and field names.
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import java.util.List;
public interface BookRepository extends JpaRepository<Book, Long> {
@Query("select b from Book b where b.publishedYear between :from and :to order by b.title")
List<Book> findPublishedBetween(@Param("from") int from, @Param("to") int to);
}Points to notice:
Bookis the entity name, not the table namebooks.b.publishedYearis the Java field, not a column name.:fromand:toare named parameters, bound by@Param.
Named and positional parameters
Prefer named parameters. They survive reordering of method arguments. Positional parameters use ?1, ?2 and so on, and they depend on argument order.
@Query("select b from Book b where b.title like ?1")
List<Book> findByTitlePattern(String pattern);If you compile with the -parameters flag (Spring Boot's Maven and Gradle plugins enable it by default), @Param is optional for named parameters. Keeping @Param is still safe and explicit.
Never concatenate values into the query
Always bind values as parameters. Building a query string from user input opens the door to injection. Bound parameters are sent separately from the query text, so the database never interprets them as code.
@Query("select b from Book b where lower(b.title) like lower(concat('%', :text, '%'))")
List<Book> search(@Param("text") String text);The concat call runs inside the query, and :text is still a bound parameter.
Using SpEL for entity names and wildcards
Spring Data supports SpEL (Spring Expression Language) in @Query. Two forms are common:
#{#entityName}inserts the entity name, which helps in generic base repositories.:#{#param}and?#{...}evaluate expressions against method arguments.
Spring Data also adds % wildcards for you with a like expression when you write like %:text%:
@Query("select b from Book b where b.title like %:text%")
List<Book> titleContains(@Param("text") String text);Use this only if it reads clearly to your team. The explicit concat form is easier to understand.
Joins and join fetch
You can join associations directly in JPQL. A plain join filters rows but does not load the association. A join fetch loads it in the same select.
@Query("select b from Book b join fetch b.author where b.publishedYear = :year")
List<Book> findByYearWithAuthor(@Param("year") int year);Without join fetch, reading book.getAuthor().getName() on each result would trigger one extra select per book. That is the N+1 problem, which a later chapter covers in depth.
| Form | Filters rows | Loads association |
|---|---|---|
| `join b.author a where a.name = :n` | Yes | No, it stays a lazy proxy |
| `join fetch b.author` | Yes (inner join) | Yes |
| `left join fetch b.author` | No | Yes, and keeps books with no author |
Fetching collections
Be careful with join fetch on collections such as Author.books:
- The result can contain the same
Authorseveral times, one per book row. Useselect distinct a from Author a join fetch a.books. Recent Hibernate versions deduplicate entity results automatically, butdistinctdocuments the intent. - Never combine
join fetchof a collection with pagination. Hibernate cannot limit rows in SQL then, so it loads everything and pages in memory. It logs a warning (HHH90003004). Page the parent query first, or use a different approach. - Fetching two
Listcollections in one query can raise aMultipleBagFetchException.
Selecting values, aggregates and constructors
A query does not have to return entities. You can select single values or aggregates.
@Query("select count(b) from Book b where b.author.name = :name")
long countByAuthorName(@Param("name") String name);
@Query("select max(b.publishedYear) from Book b")
Integer latestYear();max returns null when there are no rows, so use a wrapper type such as Integer, not int.
You can also build a DTO directly with a constructor expression. The class name must be fully qualified:
public record BookSummary(String title, int publishedYear) {
}@Query("select new com.example.catalog.BookSummary(b.title, b.publishedYear) from Book b")
List<BookSummary> findSummaries();Replace com.example.catalog with your own package. A later chapter on projections shows simpler alternatives.
Modifying queries
@Query can also run update and delete statements. Mark the method with @Modifying and make sure a transaction is active.
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.transaction.annotation.Transactional;
@Transactional
@Modifying(clearAutomatically = true, flushAutomatically = true)
@Query("update Book b set b.publishedYear = :year where b.id = :id")
int updateYear(@Param("id") Long id, @Param("year") int year);The return value is the number of affected rows. A bulk statement goes straight to the database and skips the persistence context. This has consequences:
- Entities already loaded in the current persistence context are not updated, so they hold stale values.
clearAutomatically = trueclears the persistence context after the statement, so later reads hit the database.flushAutomatically = trueflushes pending changes first, so they are not lost or overwritten by the clear.- Lifecycle callbacks, cascades, auditing and
@Versionincrements do not run for bulk statements.
Use bulk updates for large set-based changes. For a single entity, load it and change it through its setters instead.
Native SQL queries
Set nativeQuery = true to send plain SQL to the database. Table and column names are then used, not entity names.
@Query(value = "select * from books where published_year >= :year", nativeQuery = true)
List<Book> findNativeFromYear(@Param("year") int year);Use native queries when you need database-specific features such as window functions, full-text search or vendor functions. The costs are real:
- The query is not validated at startup. A typo fails only when the query runs.
- It ties your code to one database dialect.
- Column names must match the schema, including naming strategy effects such as
published_year. - Result mapping to entities needs every column the entity maps. Selecting a subset into an entity fails.
For partial results from a native query, return an interface projection or a Tuple, not the entity.
Pagination with native queries
Spring Data cannot always derive a count query from native SQL, so supply one:
@Query(
value = "select * from books where published_year >= :year",
countQuery = "select count(*) from books where published_year >= :year",
nativeQuery = true)
Page<Book> findNativePage(@Param("year") int year, Pageable pageable);JPQL queries that return a Page get an automatic count query, but you can also give countQuery for complex queries, especially those with joins or group by.
Sorting and paging with @Query
You can add a Pageable or Sort parameter to a JPQL query. Spring Data appends the order by clause and limit for you.
@Query("select b from Book b where b.author.name = :name")
Page<Book> findByAuthor(@Param("name") String name, Pageable pageable);A Sort is applied to the aliased entity, so a sort property such as title becomes b.title. For native queries, dynamic sort is unreliable. Write the order by into the SQL, or sort in a way you control.
Choosing between the approaches
| Need | Best choice |
|---|---|
| One or two simple conditions | Derived query method |
| Joins, aggregates, readable name | JPQL with `@Query` |
| Load an association in one select | `join fetch` or `@EntityGraph` |
| Set-based update or delete | `@Modifying` JPQL |
| Database-specific SQL | Native query |
| Conditions chosen at runtime | Specifications or Querydsl, not `@Query` |
Common errors
QueryCreationExceptionorBeanCreationExceptionat startup. The JPQL has a typo, such as a wrong field name or entity name. Read the message and check names against the Java classes, not the tables.Named parameter not bound. The:namein the query has no matching@Param, or the names differ.TransactionRequiredExceptionon a modifying query. Add@Transactionalto the repository method or the calling service.- Stale data after a bulk update. Use
clearAutomatically = true, or reload the entity after the update. - Using table names in JPQL. Write
Book, notbooks. LazyInitializationExceptionafter a plainjoin. A plain join does not load the association. Usejoin fetch.
Exercise
You write @Query("select b from Book b join fetch b.author where b.publishedYear = :year") and call it from a service method. Why does book.getAuthor().getName() no longer cause one extra select per book, and what must you avoid if you also want to return a Page<Book> from a query that join-fetches a collection?
Show answer
join fetch loads the Author in the same select as the books, so the author is already initialized and no lazy proxy has to be resolved per book. For a join fetch on a collection, do not combine it with pagination. Hibernate cannot apply the limit in SQL because the join multiplies rows, so it loads all rows and pages in memory. Page the parent entities first, or use another strategy.
Exercise
A @Modifying query sets publishedYear for a book that was loaded earlier in the same transaction. After the update, book.getPublishedYear() still shows the old value. Why, and which attribute of @Modifying fixes it?
Show answer
The bulk update runs directly in the database and does not change entities held in the persistence context. Setting clearAutomatically = true clears the context after the statement, so the next read loads the new value. Adding flushAutomatically = true makes sure pending changes are written first.