首页 > 解决方案 > 查询公共方法验证失败,spring jpa?

问题描述

我正在创建一个 api 来从数据库中查询并返回结果。

这是请求

@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);
}

表类

@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)!

标签: javasqlspringjpa

解决方案


您必须在查询中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);

推荐阅读