Spring Boot 2.6 JPA中@Query无nativeQuery属性,该如何解决?
Spring Boot JPA原生SQL查询nativeQuery属性未定义问题
场景与问题
使用Spring Boot 2.6及Spring Boot JPA 2.6.4版本,尝试通过以下原生SQL查询MySQL表的最后5条记录:
@Query(value="SELECT * FROM produit p ORDER BY p.id DESC LIMIT 5") public Collection<Produit> getProduit();
按常规需在@Query中添加nativeQuery = true属性,但提示该属性未定义,排查方向如下:
解决要点
- 检查@Query注解的导入包:必须导入
org.springframework.data.jpa.repository.Query,而非javax.persistence.Query(JPA原生注解无nativeQuery属性)。 - 确认依赖与接口继承关系:
- 项目需正确引入
spring-boot-starter-data-jpa依赖,版本匹配Spring Boot 2.6.x; - DAO接口必须继承Spring Data JPA的
CrudRepository或JpaRepository接口,否则@Query注解无法被Spring Data JPA识别。
- 项目需正确引入
正确代码示例
import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.CrudRepository; import java.util.Collection; public interface ProduitRepository extends CrudRepository<Produit, Long> { @Query(value="SELECT * FROM produit p ORDER BY p.id DESC LIMIT 5", nativeQuery = true) Collection<Produit> getProduit(); }
内容的提问来源于stack exchange,提问作者dbarasuk
相关产品推荐
相关产品推荐

