@Query Annotation in Spring Data JPA — JPQL and Native SQL
Fast recall
Quick revision
Core answer
Whether you can write JPQL/native queries and know the @Modifying + @Transactional requirement for writes
Forgetting @Modifying/@Transactional on UPDATE/DELETE, or using table names in JPQL
Show JOIN FETCH for N+1, named vs positional params, and when nativeQuery=true is justified
Interview-ready guide
Interview answer
For example, @Query("select o from Order o where o.status=:status order by o.createdAt desc") List
@Query Annotation in Spring Data JPA — JPQL and Native SQL
Direct Answer
@Query attaches a JPQL query or, with nativeQuery=true, database SQL to a repository method. JPQL uses entity names and mapped attributes; native SQL uses table/column names and database syntax. Use it when a derived method would be unclear or cannot express the required shape. There is no useful universal method-name character limit.
Common Mistakes & Pitfalls
- Missing
@Modifyingon UPDATE/DELETE — Hibernate assumes a read query and throws. - No
@Transactional— even with@Modifying, writes need a transaction. - Table names in JPQL —
FROM ordersfails; use the entityFROM Order. - Native query and entity state — native results aren't managed; changes won't auto-flush unless you
save().
Check your understanding
Answer these without looking back at the article.
- What are derived query methods in Spring Data JPA?
- What is the findBy...Containing and findBy...Like in Spring Data JPA?
- How do you use findBy...In() and findBy...Between() in Spring Data?
Looking for a structured roadmap?
Every module on this page is also part of the full Java backend interview track.