[英]Error while creating custom queries in spring boot
我是春季启动新手,在向代码添加查询时遇到以下错误,
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:我正在关注这个教程页面 - 链接到教程
提前致谢 !!
错误很明显:
查询方法public abstract rest.Test rest.services.TestService.findByXY(java.lang.String)的验证失败!
JPQL查询的语法不正确:
@Query("select id, x, y from test where x = :x")
Employee findByXY(@Param("x") String x);
选择一个Test
并返回一个与您的查询匹配的类型:
@Query("select t from Test t where t.x = :x")
Test findByXY(@Param("x") String x);
否则,如果要像hrdkisback建议的那样,通过添加nativeQuery = true
来指定本机查询。
这个查询:
select id, x, y from test where x = :x
返回3个参数id
, x
和y
而不是Employee
类型的对象
因此返回类型应该是List<Object[]>
而不是Employee
@Query("select id, x, y from test where x = :x")
List<Object[]> findByXY(@Param("x") String x);
然后你可以像这样迭代这个列表:
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])
);
}
您已经编写了native
查询,请尝试传递nativeQuery true
@Query("select id, x, y from test where x = :x", nativeQuery = true)
或者您可以编写HQL
查询
@Query("SELECT t.id, tx, ty FROM Test t where tx = :x")
有关详细信息,请参阅此链接。 https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#jpa.query-methods.at-query
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.