Spring Boot报FactoryBean创建异常,JPA自定义查询验证失败如何解决?
错误原因
@Query注解默认使用JPQL语法,该语法面向Java实体类设计,不支持原生SQL的SELECT *写法,也要求查询对象必须为实体类名、筛选条件必须对应实体类的属性名。你当前写的查询语句是原生SQL语法,不符合JPQL校验规则,因此启动时查询验证失败抛出异常。
修复方案
有两种可选择的修复方式:
方案1:改为JPQL写法(推荐)
按照JPQL语法规则修改查询语句,语句中的对象、字段对应实体类的类名和属性名即可:
public interface RapportoRepository extends JpaRepository<Rapporto, Integer> { // 注意此处Rapporto为实体类名,r.idCantiere为实体类中对应IdCantiere的属性名,需和你实际实体类属性名完全一致 @Query("SELECT r FROM Rapporto r WHERE r.idCantiere = :IdCantiere") List<Rapporto> findbycantiere(@Param("IdCantiere") int IdCantiere); }
针对这种单条件查询场景,你甚至可以直接省略@Query注解,直接按Spring Data JPA命名规则定义方法名即可自动生成查询,代码更简洁:
public interface RapportoRepository extends JpaRepository<Rapporto, Integer> { List<Rapporto> findByIdCantiere(@Param("IdCantiere") int IdCantiere); }
方案2:声明使用原生SQL查询
如果确实需要使用原生SQL编写查询逻辑,只需在@Query注解中添加nativeQuery = true参数,告知JPA按照原生SQL语法解析语句即可:
public interface RapportoRepository extends JpaRepository<Rapporto, Integer> { // 此处Rapporto为数据库表名,IdCantiere为数据库表中的字段名,需和实际库表结构一致 @Query(value = "SELECT * FROM Rapporto where IdCantiere=:IdCantiere", nativeQuery = true) List<Rapporto> findbycantiere(@Param("IdCantiere") int IdCantiere); }
内容的提问来源于stack exchange,提问作者riki
相关产品推荐
相关产品推荐

