Spring Data @Query注解支持JPA语法还是HQL?技术问询(含代码)
Great question! Let's break this down clearly for you:
Default: JPA Standard JPQL
Out of the box, the@Queryannotation uses JPQL (Java Persistence Query Language)—this is the official query language defined by the JPA specification. Any JPA-compliant provider (like Hibernate, EclipseLink, or OpenJPA) will recognize and execute valid JPQL statements, making your queries portable across different implementations.HQL Compatibility (when using Hibernate as your JPA provider)
HQL is Hibernate's extended superset of JPQL, adding proprietary features like advanced join syntax, custom functions, and locking hints that aren't part of the JPA standard. If your project uses Hibernate as its underlying JPA provider (the most common setup), you can safely write HQL in your@Queryannotations—Hibernate will parse and run these without any issues.
Analyzing your code example
Your query:
@Query("SELECT t.title FROM Todo t where t.id = :id")
This is a standard JPQL statement, so it will work seamlessly with any JPA provider. If you wanted to use HQL-specific syntax (like pessimistic locking with FOR UPDATE), you could adjust it to:
@Query("SELECT t.title FROM Todo t where t.id = :id FOR UPDATE")
And this would run perfectly as long as Hibernate is your JPA provider.
A quick side note: If you ever need to execute native SQL instead of JPQL/HQL, just add the nativeQuery = true parameter to the annotation:
@Query(value = "SELECT title FROM todo WHERE id = :id", nativeQuery = true)
内容的提问来源于stack exchange,提问作者johnstreip

