Sub topic 9
Custom queries with @Query
This chapter assumes you can write derived query methods, know basic SQL joins, and have the Author and Book entities from earlier chapters. Derived methods work well for simple filters. When a method name becomes unreadable, or you need a join, an aggregate or a vendor-specific feature, use @Query.
JPQL queries
JPQL (Jakarta Persistence Query Language) looks like SQL, but it queries entities and their fields, not tables and columns. You write Book and b.publishedYear, not books and published_year.
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);
@Query("select b from Book b where lower(b.title) like lower(concat('%', :text, '%'))")
List<Book> searchTitle(@Param("text") String text);
}Spring validates JPQL when the application starts. A typo such as b.publishYear fails the startup, not a request at runtime.
Named parameters
Bind values with :name placeholders and @Param. Positional placeholders such as ?1 also work, but they break silently when you reorder arguments. Never build the query by concatenating strings, because that opens the door to SQL injection.
Joins and fetching
A join fetch loads an association in the same select. This is one way to avoid the N+1 problem covered later.
@Query("select b from Book b join fetch b.author where b.publishedYear = :year")
List<Book> findByYearWithAuthor(@Param("year") int year);Native SQL
Set nativeQuery = true to send plain SQL to the database. Now you use table and column names, and the query is tied to one database vendor.
@Query(value = "select * from books where published_year < :year", nativeQuery = true)
List<Book> findOlderThan(@Param("year") int year);Native queries are not checked at startup. They fit database-specific features such as window functions or full-text search.
Modifying queries
Queries that change data need @Modifying and a transaction.
@Modifying(clearAutomatically = true)
@Transactional
@Query("update Book b set b.publishedYear = :year where b.id = :id")
int updateYear(@Param("id") Long id, @Param("year") int year);A bulk update runs directly in the database and skips the persistence context. Entities already loaded keep their old values. clearAutomatically = true clears the context after the update so later reads return fresh data. The return value is the number of rows changed.
Common errors
| Symptom | Likely cause |
|---|---|
| Startup fails with "unknown path" | A JPQL field name does not match the entity field |
| `TransactionRequiredException` | A `@Modifying` query runs without a transaction |
| Stale values after an update | The persistence context was not cleared |
| `Named parameter not bound` | `@Param` name differs from the `:name` placeholder |
Exercise
You run a @Modifying update query, then call findById for an entity that was loaded earlier in the same transaction. It still shows the old value. Why, and how do you fix it?
Show answer
A bulk update goes straight to the database and does not change entities held in the persistence context, so findById returns the cached instance. Add clearAutomatically = true to @Modifying, or call EntityManager.clear() after the update, so the next read reloads from the database.
Exercise
Write a JPQL query method that returns all books whose author name equals a given name, loading the author in the same select.
Show answer
@Query("select b from Book b join fetch b.author a where a.name = :name") List<Book> findByAuthorName(@Param("name") String name);