Spring JPA의 SQL 집계 GROUP BY 및 COUNT

판닌 드라 :

SQL 테이블이 있습니다.

@Table(name = "population_table")
public class Population {
  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Long id;
  private String country;
  private String state;
  private String area;
  private String population;
}

출력 클래스가 List of Count 인 국가 및 주별로 그룹화 된 개수를 얻고 싶습니다.

  private static class Count {
    private String country;
    private String state;
    private long count;
  }

나는 쿼리가

SELECT country, state, Count(*)
FROM population_table
GROUP BY country, state

하지만 JPA 사양을 사용하여 이것을하고 싶습니다. 스프링 부트에서 JPA 사양을 사용하여 어떻게 이것을 달성 할 수 있습니까?

Nitish Kumar :

SpringData JPA 에서 SpringData JPA Projections사용하여이를 달성 할 수 있습니다.

사용자 지정 Repository방법을 다음과 같이 만듭니다.

@Repository
public interface PopulationRepository extends JpaRepository<Population, Long> {

@Query("select new com.example.Count(country, state, count(*) )
       from Population p
       group by p.country, p.state")
public List<Count> getCountByCountryAndState();

}

또한 Count이 프로젝션을 처리 할 클래스 의 특정 생성자를 정의해야합니다.

private static class Count {
 private String country;
 private String state;
 private long count;

 //This constructor will be used by Spring Data JPA 
 //for creating this class instances as per result set
 public Count(String country,String state, long count){
   this.country = country;
   this.state = state;
   this.count = count;
 }
}

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

TOP 리스트

뜨겁다태그

보관