In my Spring Boot project I have this pom:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.3.1.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
....
I want to use a custom native query in one of the repositories
@Query(nativeQuery=true, "select * from question q where q.id < 5")
public Collection<QuestionEntity> queryAnnotated();
But as I want to give the parameter nativeQuery = true, I get a syntax error
Syntax error on token ""select * from question q where q.id < 5"", invalid MemberValuePair
The @Query annotation declares finder queries directly on repository methods. While similar @NamedQuery is used on domain classes, Spring Data JPA @Query annotation is used on Repository interface. This frees the domain classes from persistence specific information, which is a good thing.
The @Query annotation supports both JPQL and SQL queries.
We can use @Query annotation to specify a query within a repository. Following is an example. In this example, we are using native query, and set an attribute nativeQuery=true in Query annotation to mark the query as native. We've added custom methods in Repository in JPA Custom Query chapter.
The @Query annotation takes precedence over named queries, which are annotated with @NamedQuery or defined in an orm.xml file. It's a good approach to place a query definition just above the method inside the repository rather than inside our domain model as named queries.
You should use your @Query like this:
@Query(nativeQuery = true, value="select * from question q where q.id < 5")
public Collection<QuestionEntity> queryAnnotated();
The value
tag was missing in your example. The question
table and the column q.id
should exactly match with your table and column names of your Database.
In my test application it works:
@Repository
public interface QuestionRepository extends JpaRepository<Question, long>{
@Query(nativeQuery=true, value="SELECT * FROM Question q where q.id < 5")
public Collection<Question> findQuestion();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With