-
[Spring] Native Query 사용 시 Failed to convert from type [java.lang.Object[]] to type 에러Spring 2021. 10. 21. 16:07
문제 상황:
스프링에서 JAVA와 Tibero를 사용하는데 JPA를 사용해서 DB를 조회 할 때 처럼 Tibero에서만 지원해주는 함수를 사용하기 위해 em.createNativeQuery() 을 이용하여 native query를 사용하였다.
private final EntityManager em; public FileRepositoryImpl(EntityManager em) { this.em = em; } Query nativeQuery = em.createNativeQuery("SELECT * FROM FILE_TB;") List<FileEntity> fileEntities = nativeQuery.getResultList(); // 예시이기 때문에 tibero에서만 지원하는 함수를 사용하지 않고 간단한 native query를 사용했다. System.out.println(fileEntities); // [[Ljava.lang.Object;@555e29d7, [Ljava.lang.Object;@6fa83e63, [Ljava.lang.Object;@336107c6, [Ljava.lang.Object;@5c8999de // 에러 발생 Failed to convert from type [java.lang.Object[]] to type [test.model.FileEntity] for value '{9e81c409-1127-48d9-a0e2-cfe323ef7c1d, e293c45c-3a33-41b6-8c97-20233249a4ae, 0, null, d6e6a894-721e-49f3-a149-ade76d6c0119, test2, null, 0, fde5f21f-d516-49cb-be19-223d6cbd132b, Y, N, N, 2021-10-20 19:35:03.0, 2021-10-20 19:35:03.0, fde5f21f-d516-49cb-be19-223d6cbd132b, null, null, null, null, N, N}'; nested exception is org.springframework.core.convert.ConverterNotFoundException: No converter found capable of converting from type [java.lang.String] to type [test.model.FileEntity]
DB 조회 리스트를 출력해보니 [[Ljava.lang.Object;@555e29d7.... 같은 class형식:클래스 이름:주소값의 형태로 출력이 되었다. 클래이스 이름은 FileEntity로 받았기 때문에 FileEntity로 찍여야 하는데 왜 최상위 클래스인 Object가 출력 되는 것일까 한참을 고민하였다.
이 문제 때문에 Object 형태의 객체를 FileEntity 형태의 객체에 담으면서 변화하는데 에러가 발생하였다. 구글에서 검색해 보고 StackOverflow도 열심히 찾아 보았으나 해결 예시는 1. DB column과 key값이 정확히 일치하는 POJO (필드 변수만 있는 클래스)를 생성해서 데이터를 받던지 2. @SqlResultSetMapping 를 사용하던지 3. Jackson ObjectMapper를 사용하라고 하였다. 하지만 문제는 매우 간단한 곳에 있었다.
해결:
private final EntityManager em; public FileRepositoryImpl(EntityManager em) { this.em = em; } Query nativeQuery = em.createNativeQuery("SELECT * FROM FILE_TB;", FileEntity.class) List<FileEntity> fileEntities = nativeQuery.getResultList();
em.createNativeQuery에 두번째 파라미터로 FileEntity.class를 넣어주어야 했다. 즉 DB 데이터가 반환 할 형식을 지정해 주어야 했다. 반환할 형식을 지정해 주지 않으면 조회 결과는 들어 있지만 key값 없이 최상위 객체인 Object에 담겨 반환 되는 것을 알 수 있었다.
'Spring' 카테고리의 다른 글
[Spring] o.h.e.jdbc.spi.SqlExceptionHelper - JDBC-90611:Specified column name was not found. - column 에러 (0) 2021.12.08 [Spring Logging] Slf4j - log4j2 사용 시 기존 logback, log4j 와 충돌 에러 (0) 2021.11.29 [Spring] Logging slf4j - log4j, logback, log4j2 (0) 2021.11.29 [Spring] JPA update query error (0) 2021.10.14 [Spring] ModelMapper configuration errors (0) 2021.09.30