-
Spring - JPA distinct 여러 컬럼 사용하기Spring 2024. 3. 12. 22:34반응형
Spring JPA를 사용할 때 distinct를 사용하는 경우 @Query 어노테이션을 사용해서 처리합니다.
distinct 여러 컬럼을 할 때의 코드에 대해서 알아보겠습니다.
JPA repository 코드
@Query(value = "select distinct type, code from table", nativeQuery = true) List<Object> findDistinct();
distinct 컬럼 한 개일때는 String으로 처리가 가능하지만, 두개 이상의 경우에는 Object로 결과값을 받아야 합니다.
JPA repository 조회하는 Service layer
List<Object> objects = repository.findDistinct(); List<Result> result = objects.stream() .map(x ->{ Object[] obj = (Object[]) x; String type = (String) obj[0]; String code = (String) obj[1]; return new Result(type, code); }).collect(Collectors.toList());
Object를 Object[] 로 casting해서 [0], [1] 값을 가져오면 됩니다.
반응형'Spring' 카테고리의 다른 글
Spring - JPA InvalidDataAccessApiUsageException (0) 2024.03.25 Spring - JPA @Modifying return value (0) 2024.03.25 Spring - JPA on duplicate key update (MySQL) (0) 2024.02.13 Spring - JPA Entity에서 @Column 필드 리스트로 만들기 (0) 2024.02.13 Spring - Resilience4j circuit breaker example (0) 2024.01.09