我正在创建一个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);
}表类
@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)!发布于 2020-05-30 14:44:55
在查询中,您必须在实体名称AppConfig之后添加别名n,应该如下所示:
@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 data query方法处理,只需确保重命名该方法以使用实体的字段名称:
List<AppConfig> findByAppCodeAndAppVersion(String appCode, String appVersion);发布于 2020-05-30 14:45:32
试试这个:
@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);https://stackoverflow.com/questions/62098753
复制相似问题