ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • spring data jpa 사용 시에 group by 는 어떻게 사용하면 편할까
    카테고리 없음 2023. 2. 19. 18:08

    쿼리 dsl을 이용해서 쉽게 group by 를 할 수는 있는데
    repository 리턴타입을 어떻게 세팅하면 될까?

    @Query("select s from Sampe s group by s.companyId")
    List<Map<Long, Sample>> findByCompanyGroupBy();

    별론가?
    리턴타입은 List<Object[]> 가 된다.
    어플리케이션에서 group by 해 보자

    list.stream()
    .collect(Collectors.groupingBy(Sample::companyId))

    쉽네.
    companyId 별로 그룹핑해서 처리하는 비지니스를 계속해 보자.

    list.stream()
    .collect(Collectors.groupingBy(Sample::companyId))
    .entrySet().stream()
    .map(...Entry<Long, List<Sample>>)

    Sample 리스트로 최종 결과를 만들자

    list.stream()
    .collect(Collectors.groupingBy(Sample::companyId))
    .entrySet().stream()
    .map(...Entry<Long, List<Sample>>)
    .flatMap(List::stream)
    .toList()
Designed by Tistory.