在spring boot中创建自定义查询时出错

时间:2017-12-14 07:23:53

标签: java mysql spring-mvc spring-boot spring-data

我是初次启动时的新手,在向代码添加查询时遇到以下错误

  

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 个答案:

答案 0 :(得分:1)

错误很明显:

  

对方法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);

否则,如果您想通过添加nativeQuery = true建议hrdkisback,请指定原生查询。

答案 1 :(得分:1)

此查询:

select id, x, y from test where x = :x

返回3个参数idxy,而不是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])
    );
}

答案 2 :(得分:1)

您已编写native查询,请尝试将nativeQuery传递为

@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