首页 文章

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

提问于
浏览
1

我是 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 回答

  • 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

  • 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

    这个查询:

    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])
        );
    }
    

相关问题