java - 查询公共方法验证失败,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)!
解决方案
您必须在查询中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);
推荐阅读
- python - 如何在 pyomo 的目标函数的求和界中包含一个变量?
- javascript - 单击容器外部时隐藏展开的菜单:如何使用代码片段
- python - 将 python pandas 数据框展平为列表
- python - 无法导入接口:ModuleNotFoundError: No module named 'interface'
- java - TestNG 组不执行 @BeforeMethod
- php - 本地开发中的 ENV 缓存问题(PHP-FPM、NGINX 和 LARAVEL)
- angular - canActivate AuthGuard 不重定向到登录页面
- python - 在 MacOS Catalina 上安装 GDAL 失败
- python - “conv_base.output”和“conv_base.input”在这段代码中是什么意思或做什么?
- emacs - Emacs Cx C-; 评论行不工作