【问题标题】:Spring Data JPA [Unknown column '...' in 'where clause']Spring Data JPA ['where 子句'中的未知列'...']
【发布时间】:2021-12-24 13:43:04
【问题描述】:

我正在开发一个 Spring 项目和 MySQL 数据库系统。

我有一个包含“list_id”列的表 我在 Java 类中有这个列的变量。但是,如您所见,这两个名称是不同的:

    @Column(name = "list_id")
    private int listId;

我正在做这个查询:

   @Query(value="select * from words_list WHERE list_id=listId", nativeQuery=true)
   List<WordList> neverTested(@RequestParam("listId") int listId);

我尝试将它们放入控制器类

    public List<WordList> neverTested(@RequestParam int listId){

    return wordListRepository.neverTested(listId);
}

我总是收到这个错误:

java.sql.SQLSyntaxErrorException: Unknown column 'listId' in 'where clause'

即使我很确定自己的方式,但听起来问题出在名称上

【问题讨论】:

  • @RequestParam 在 JpaRepository 中做什么?使用@Param 将值绑定到sql 语句。此外,如果您有 -parameters 编译器标志,则不必使用 @Param

标签: java sql spring jpa


【解决方案1】:

在listId前加一个“:”,像这样:

 @Query(value="select * from words_list WHERE list_id = :listId", nativeQuery=true)
   List<WordList> neverTested(@RequestParam("listId") int listId);

【讨论】:

    【解决方案2】:

    你必须在你的参数前写一个冒号 像这样

     @Query(value="select * from words_list WHERE list_id=:listId", nativeQuery=true)
    

    【讨论】:

      【解决方案3】:

      使用org.springframework.data.repository.query.@Param 将方法参数传递给查询, 而不是org.springframework.web.bind.annotation.@RequestParam


      @Query 查询字符串示例:

      "select * from words_list WHERE list_id=:listId"
      

      命名参数在查询字符串中由一个冒号表示,后跟参数名称。

      结合@Query 和@Param 注释的示例:

      @Query(value="select * from words_list WHERE list_id=:listId", nativeQuery=true)
      List<WordList> neverTested(@Param("listId") int listId);
      

      【讨论】:

        猜你喜欢
        • 2016-04-29
        • 2015-09-20
        • 2017-01-18
        • 2016-11-26
        • 2011-06-03
        • 1970-01-01
        • 2020-07-10
        • 1970-01-01
        相关资源
        最近更新 更多