Arash Taheri
Arash Taheri

Reputation: 73

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

Upvotes: 7

Views: 47210

Answers (2)

Patrick
Patrick

Reputation: 12734

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();
}

Upvotes: 22

Prateek Sharma
Prateek Sharma

Reputation: 269

You can try this. Change the query and method as per your business requirement. Hope it works.

public interface UserRepository extends JpaRepository<User, Long> {

  @Query(value = "SELECT * FROM USERS WHERE EMAIL_ADDRESS = ?0", nativeQuery = true)
  User findByEmailAddress(String emailAddress);
}

Upvotes: 0

Related Questions