在 Spring 中将 nativeQuery=true 与 @Query 一起使用 - 引导不起作用

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

在我的 Spring 引导项目中,我有这个 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>
....

我想在其中一个存储库中使用自定义本机查询

@Query(nativeQuery=true, "select * from question q where q.id < 5")
public Collection<QuestionEntity> queryAnnotated();

但是当我想给参数 nativeQuery = true 时,我得到一个语法错误

Syntax error on token ""select * from question q where q.id < 5"", invalid MemberValuePair

你可以试试这个。根据您的业务需求更改查询和方法。希望有用。

public interface UserRepository extends JpaRepository<User, Long> {

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

你应该像这样使用你的@Query:

@Query(nativeQuery = true, value="select * from question q where q.id < 5")
public Collection<QuestionEntity> queryAnnotated();

您的示例中缺少 value 标记。 question table 和列 q.id 应该与数据库的 table 和列名称完全匹配。

在我的测试应用程序中有效:

@Repository
public interface QuestionRepository extends JpaRepository<Question, long>{

    @Query(nativeQuery=true, value="SELECT * FROM Question q where q.id < 5")
    public Collection<Question> findQuestion();
}