You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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属性)。
  • 确认依赖与接口继承关系:
    1. 项目需正确引入spring-boot-starter-data-jpa依赖,版本匹配Spring Boot 2.6.x;
    2. 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 16:15:41