I am new to spring boot and I am facing the below error when adding queries to my code,
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'testController': Unsatisfied dependency expressed through field 'testService'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'testService': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Validation failed for query for method public abstract rest.Test rest.services.TestService.findByXY(java.lang.String)!
below are my code files,
Test.java
@Entity
public class Test {
@Id
private int id;
@Column
private String x;
@Column
private String y;
public Test() {
}
public Test(int id, String x, String y) {
this.id = id;
this.x = x;
this.y = y;
}
}
TestService.java
public interface TestService extends CrudRepository<Test, Integer> {
@Query("select id, x, y from test where x = :x")
Employee findByXY(@Param("x") String x);
}
TestController.java
@Controller
public class TestController {
@Autowired
private TestService testService;
@GetMapping("/get-x")
public Employee findX() {
//System.out.println(testService.findByXY("123"));
return testService.findByXY("123");
}
}
PS: I am following this tutorial page - link to tutorial
Thanks in advance !!
The error is clear :
Validation failed for query for method public abstract rest.Test rest.services.TestService.findByXY(java.lang.String)!
The syntax is not correct for a JPQL query :
@Query("select id, x, y from test where x = :x")
Employee findByXY(@Param("x") String x);
Select rather a Test
and returns also a type that matches to your query :
@Query("select t from Test t where t.x = :x")
Test findByXY(@Param("x") String x);
Otherwise, specify a native query if you want to do that as hrdkisback suggested, by adding nativeQuery = true
.
This query :
select id, x, y from test where x = :x
return 3 parameters id
, x
, and y
and not an object of type Employee
So the return type should be List<Object[]>
and not Employee
@Query("select id, x, y from test where x = :x")
List<Object[]> findByXY(@Param("x") String x);
Then you can iterate through this list like this :
List<Object[]> listTest = findByXY(x);
List<Test> resultList = new ArrayList<>();
for (Object[] test : listTest) {
resultList.add(
new Test((Integer) test[0],
(String) test[1],
(String) test[2])
);
}
You have write native
query so, Try to pass nativeQuery true like
@Query("select id, x, y from test where x = :x", nativeQuery = true)
Or you can write HQL
query
@Query("SELECT t.id, tx, ty FROM Test t where tx = :x")
Please refer this link for more info. https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#jpa.query-methods.at-query
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.