我是 Spring 季启动新手,在向代码添加查询时遇到以下错误,
org.springframework.beans.factory.UnsatisfiedDependencyException:创建名为'testController'的bean时出错:通过字段'testService'表示的不满意的依赖关系;嵌套异常是org.springframework.beans.factory.BeanCreationException:创建名为'testService'的bean时出错:init方法的调用失败;嵌套异常是java.lang.IllegalArgumentException:查询方法public abstract rest.Test rest.services.TestService.findByXY(java.lang.String)的验证失败!
下面是我的代码文件,
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:我正在关注这个教程页面 - link to tutorial
提前致谢 !!
3 回答
你已经写了
native
查询,尝试传递nativeQuery true就像@Query("select id, x, y from test where x = :x", nativeQuery = true)
或者你可以写
HQL
查询@Query("SELECT t.id, t.x, t.y FROM Test t where t.x = :x")
有关详细信息,请参阅此链接 . https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#jpa.query-methods.at-query
错误很明显:
JPQL查询的语法不正确:
选择
Test
并返回与您的查询匹配的类型:否则,如果要通过添加
nativeQuery = true
来建议hrdkisback,请指定本机查询 .这个查询:
返回3个参数
id
,x
和y
而不是Employee
类型的对象所以返回类型应该是
List<Object[]>
而不是Employee
然后你可以像这样迭代这个列表: