Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use nativeQuery=true with @Query in Spring-Boot does not work

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
like image 352
Arash Taheri Avatar asked Jan 12 '16 12:01

Arash Taheri


People also ask

How does @query work in spring boot?

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.

What type of queries can be executed with the help of @query annotation?

The @Query annotation supports both JPQL and SQL queries.

What is nativeQuery true in JPA?

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.

What is @query annotation in spring boot?

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.


1 Answers

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();
}
like image 71
Patrick Avatar answered Oct 20 '22 00:10

Patrick