代码之家  ›  专栏  ›  技术社区  ›  WISHY

验证public方法spring jpa的查询失败?

  •  0
  • WISHY  · 技术社区  · 4 年前

    我正在创建一个api来从DB查询并返回结果。

    这是请求

    @RequestMapping(value = "/config", params = { "appCode", "appVersion" }, method = RequestMethod.GET)
    public List<AppConfig> getConfig(@RequestParam(value = "appCode", required = true) String appCode,
            @RequestParam(value = "appVersion", required = true) String appVersion) {
        return configRepository.findByCodeAndVersion(appCode, appCode);
    }
    

    table类

    @Entity
    @Table(name = "app_config")
    @EntityListeners(AuditingEntityListener.class)
    public class AppConfig {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(columnDefinition = "serial")
    private long id;
    @Column(name = "app_code", nullable = false)
    private String appCode;
    @Column(name = "app_name", nullable = false)
    private String appName;
    @Column(name = "api_url", nullable = true)
    private String apiUrl;
    @Column(name = "db_name", nullable = true)
    private String dbName;
    @Column(name = "app_version", nullable = false)
    private String appVersion;
    }
    

    正在进行自定义查询的存储库

    @Repository
    public interface AppConfigRepository extends CrudRepository<AppConfig, Long> {
    
    @Query("SELECT n FROM AppConfig WHERE n.appCode = ?1 and n.appVersion = ?2")
    List<AppConfig> findByCodeAndVersion(String appCode, String appVersion);
    }
    

    在运行应用程序时,我得到一个异常

    Validation failed for query for method public abstract java.util.List com.api.repository.AppConfigRepository.findByCodeAndVersion(java.lang.String,java.lang.String)!
    
    0 回复  |  直到 4 年前
        1
  •  1
  •   Mohammad Al Alwa    4 年前

    n 在实体名称之后 AppConfig 在查询中,应该是这样的:

    @Query("SELECT n FROM AppConfig n WHERE n.appCode = ?1 and n.appVersion = ?2")
    List<AppConfig> findByCodeAndVersion(String appCode, String appVersion);
    
    

    也可以在查询字符串中使用命名参数,如下所示:

    @Query("SELECT n FROM AppConfig n WHERE n.appCode = :appCode and n.appVersion = :appVersion")
    List<AppConfig> findByCodeAndVersion(String appCode, String appVersion);
    

    这样的查询可以由Spring数据查询方法来处理,只需确保重命名方法以使用实体的字段名:

    List<AppConfig> findByAppCodeAndAppVersion(String appCode, String appVersion);
    
        2
  •  0
  •   Alae Essaki    4 年前

    试试这个:

    @Query("SELECT FROM AppConfig n WHERE n.appCode = :x and n.appVersion = :y")
    List<AppConfig> findByCodeAndVersion(@Param("x")String appCode,@Param("y") String appVersion);
    

    List<AppConfig> findByAppCodeAndAppVersion(String appCode,String appVersion);