[英]Validation failed for query for method public, spring jpa?
I am creating an api to query from the DB and return the result.我正在创建一个 api 从数据库查询并返回结果。
This is the request这是请求
@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);
}
The table class表class
@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;
}
The repository where I am having custom query我有自定义查询的存储库
@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);
}
On running the application I get the exception在运行应用程序时出现异常
Validation failed for query for method public abstract java.util.List com.api.repository.AppConfigRepository.findByCodeAndVersion(java.lang.String,java.lang.String)!
You have to add the alias n
after the entity name AppConfig
in the query, it should be like:您必须在查询中的实体名称AppConfig
之后添加别名n
,它应该是:
@Query("SELECT n FROM AppConfig n WHERE n.appCode = ?1 and n.appVersion = ?2")
List<AppConfig> findByCodeAndVersion(String appCode, String appVersion);
You can also use named parameter inside the query string like this:您还可以在查询字符串中使用命名参数,如下所示:
@Query("SELECT n FROM AppConfig n WHERE n.appCode = :appCode and n.appVersion = :appVersion")
List<AppConfig> findByCodeAndVersion(String appCode, String appVersion);
And a query like this can be handled by Spring data query methods, just make sure to rename the method to use the field names of the entity: Spring 数据查询方法可以处理这样的查询,只需确保重命名方法以使用实体的字段名称:
List<AppConfig> findByAppCodeAndAppVersion(String appCode, String appVersion);
try this:尝试这个:
@Query("SELECT FROM AppConfig n WHERE n.appCode = :x and n.appVersion = :y")
List<AppConfig> findByCodeAndVersion(@Param("x")String appCode,@Param("y") String appVersion);
or you can use directly the method:或者您可以直接使用该方法:
List<AppConfig> findByAppCodeAndAppVersion(String appCode,String appVersion);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.