@Query Annotation in Spring Data JPA
Fast recall
Quick revision
Core answer
Whether you choose JPQL over native by default and know the @Modifying + @Transactional requirement for writes
Reaching for native SQL when JPQL works (losing portability), or omitting @Modifying on UPDATE/DELETE and getting a runtime exception
Mention @Modifying(clearAutomatically=true) to refresh the persistence context after a bulk update, and DTO projections via JPQL constructor expressions
Interview-ready guide
Interview answer
For example, @Query("select new com.example.OrderTotal(o.customer.id,sum(o.total)) from Order o group by o.customer.id") can return a projection. A bulk status update needs @Modifying and a transaction. Setting clearAutomatically=true avoids stale entities afterward but also detaches unrelated managed changes, so flush/clear behavior must be chosen deliberately.
@Query Annotation in Spring Data JPA
Direct Answer
@Query defines JPQL by default and native SQL when nativeQuery=true. Use it when an explicit query communicates the required projection, join, aggregation, fetch plan, or predicate more clearly than method-name derivation. Bind values as parameters. There is no meaningful universal method-name length threshold at which @Query becomes required.
Code Example
public interface OrderRepository extends JpaRepository<Order, Long> {
@Query("SELECT o FROM Order o WHERE o.status = :status") // JPQL (portable)
List<Order> byStatus(@Param("status") String status);
@Query(value = "SELECT * FROM orders WHERE notes ILIKE %:term%",
nativeQuery = true) // native: PostgreSQL ILIKE
List<Order> searchNotes(@Param("term") String term);
@Query("SELECT new com.example.dto.OrderSummary(o.id, o.total) FROM Order o")
List<OrderSummary> summaries(); // DTO projection via constructor expression
}
Common Mistakes & Pitfalls
- Native SQL by default — loses portability and field validation; use JPQL first.
- Missing
@Modifyingon UPDATE/DELETE — runtime exception;@Queryexpects SELECT otherwise. - No transaction — even with
@Modifying, the write needs a@Transactionalboundary. - Stale cache after bulk update — without
clearAutomatically = true, the next read may return old cached entities.
Check your understanding
Answer these without looking back at the article.
- What is the difference between @Query with JPQL and nativeQuery=true?
- What is @Modifying and when do you need it?
- How do you return a projection (subset of fields) with @Query?
Looking for a structured roadmap?
Every module on this page is also part of the full Java backend interview track.