개발 & IT/백엔드
[Spring Boot] JPA native query to dto throw error
개발자 제식이
2022. 12. 19. 20:50
nativequery의 결과를 dto에 담으려고 하니 아래와 같은 에러 발생
No converter found capable of converting from type [org.springframework.data.jpa.repository.query.AbstractJpaQuery$TupleConverter$TupleBackedMap] to type
https://www.baeldung.com/jpa-queries-custom-result-with-aggregation-functions
jpa 쿼리는 보통 맵핑된 엔티티 인스턴스를 결과로 생성하지만,, 네이티브 쿼리를 이용한 결과는 object를 반환한다.
그래서 아래와 같이 Object로 정의해서 엑세스가 가능하지만,
key, value 형태의 리턴이 이루어지지 않으므로 다루기 어렵다.
@Query(value = "SELECT a.id as id,"
+ " b.B"
+ " a.C"
+ " d.D"
+ " d.E"
+ " d.F"
+ " FROM A a"
+ " LEFT OUTER JOIN B b ON a.b_id = b.id"
+ " LEFT OUTER JOIN C c ON b.c_id = c.id"
+ " LEFT OUTER JOIN D d ON a.d_id = d.id"
+ " WHERE c.id = :id"
, countQuery = "SELECT count(*)"
+ " FROM A a"
+ " LEFT OUTER JOIN B b ON a.b_id = b.id"
+ " LEFT OUTER JOIN C c ON b.c_id = c.id"
+ " LEFT OUTER JOIN D d ON a.d_id = d.id"
+ " WHERE c.id = :id", nativeQuery = true)
Page<Object> getList(@Param("id") String id, Pageable pageable);
그러므로 spring boot의 interface 기반 데이터 프로젝션을 사용하여 데이터를 바인딩한다.
https://www.baeldung.com/spring-data-jpa-projections
public interface TestInterface {
String getId();
String getB();
String getC();
String getD();
String getE();
String getF();
}
@Query(value = "SELECT a.id as id,"
+ " b.B"
+ " a.C"
+ " d.D"
+ " d.E"
+ " d.F"
+ " FROM A a"
+ " LEFT OUTER JOIN B b ON a.b_id = b.id"
+ " LEFT OUTER JOIN C c ON b.c_id = c.id"
+ " LEFT OUTER JOIN D d ON a.d_id = d.id"
+ " WHERE c.id = :id"
, countQuery = "SELECT count(*)"
+ " FROM A a"
+ " LEFT OUTER JOIN B b ON a.b_id = b.id"
+ " LEFT OUTER JOIN C c ON b.c_id = c.id"
+ " LEFT OUTER JOIN D d ON a.d_id = d.id"
+ " WHERE c.id = :id", nativeQuery = true)
Page<TestInterface> getList(@Param("id") String id, Pageable pageable);
반응형