WISHY
WISHY

Reputation: 11999

Validation failed for query for method public, spring jpa?

I am creating an api to query from the DB and return the result.

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

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

Upvotes: 0

Views: 240

Answers (2)

Alae Essaki
Alae Essaki

Reputation: 78

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

Upvotes: 0

Mohammad Al Alwa
Mohammad Al Alwa

Reputation: 702

You have to add the alias n after the entity name AppConfig in the query, it should be like:

@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:

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

Upvotes: 1

Related Questions