[英]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.