Spring Data JPA原生查询报Unknown column 'listId' in 'where clause'如何解决
问题解决方法
错误原因
- 原生SQL语句直接写
list_id=listId,执行时MySQL会将listId识别为数据表的字段名,你的表中不存在该字段,因此抛出字段不存在错误 - Repository层方法错误使用了
@RequestParam注解:该注解是Controller层用于接收HTTP请求参数的,Spring Data JPA的Repository参数绑定需要使用@Param注解,导致方法入参没有正确绑定到SQL语句中
修复方案
选择以下任意一种方案修改Repository层的代码即可:
方案1:使用索引占位符绑定参数
按参数顺序用?+序号的格式绑定,序号从1开始对应方法的第N个参数:
@Query(value="select * from words_list WHERE list_id=?1", nativeQuery=true) List<WordList> neverTested(int listId);
方案2:使用命名参数绑定参数(更推荐,可读性更高)
给方法参数加@Param注解指定参数名,SQL中用:参数名的格式绑定:
// 注意导入org.springframework.data.repository.query.Param @Query(value="select * from words_list WHERE list_id=:listId", nativeQuery=true) List<WordList> neverTested(@Param("listId") int listId);
内容的提问来源于stack exchange,提问作者no thanks
相关产品推荐
相关产品推荐

