一尘不染

在Spring Boot中创建自定义查询时出错

spring-mvc

我是Spring Boot的新手,在向代码中添加查询时遇到以下错误,

org.springframework.beans.factory.UnsatisfiedDependencyException:创建名称为“
testController”的bean时出错:通过字段“
testService”表示的不满意的依赖关系;嵌套的异常是org.springframework.beans.factory.BeanCreationException:创建名称为’testService’的bean时出错:调用init方法失败;嵌套异常为java.lang.IllegalArgumentException:验证方法公共抽象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:我正在关注本教程页面- 链接至教程

提前致谢 !!


阅读 279

收藏
2020-06-01

共1个答案

一尘不染

您已经编写了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

2020-06-01