在Spring Boot中创建自定义查询时出错 [英] Error while creating custom queries in spring boot
问题描述
我是Spring Boot的新手,在向我的代码添加查询时遇到以下错误,
I am new to spring boot and I am facing the below error when adding queries to my code,
org.springframework.beans.factory.UnsatisfiedDependencyException: 创建名称为"testController"的bean时出错:不满意的依赖关系 通过字段"testService"表示;嵌套的异常是 org.springframework.beans.factory.BeanCreationException:错误 创建名称为"testService"的bean:初始化方法的调用 失败的;嵌套的异常是java.lang.IllegalArgumentException: 验证方法公共抽象rest.Test的查询失败 rest.services.TestService.findByXY(java.lang.String)!
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)!
下面是我的代码文件,
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:我正在关注本教程页面-链接到教程
PS: I am following this tutorial page - link to tutorial
预先感谢!
推荐答案
您已经编写了native
查询,因此,尝试像
You have write native
query so, Try to pass nativeQuery true like
@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
Please refer this link for more info. https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#jpa.query-methods.at-query
这篇关于在Spring Boot中创建自定义查询时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!