Spring JPA 中的 SQL 聚合 GROUP BY 和 COUNT

Pha*_*dra 3 java sql sql-server jpa spring-boot

我有一个 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;
}
Run Code Online (Sandbox Code Playgroud)

我想获得一个计数,按国家和州分组,输出类为计数列表:

  private static class Count {
    private String country;
    private String state;
    private long count;
  }
Run Code Online (Sandbox Code Playgroud)

我知道查询是

SELECT country, state, Count(*)
FROM population_table
GROUP BY country, state
Run Code Online (Sandbox Code Playgroud)

但我想使用 JPA 规范来做到这一点。如何在 Spring Boot 中使用 JPA 规范来实现这一目标?

Nit*_*mar 13

您可以通过使用Spring Data JPA 中的 Spring Data JPA 投影来实现此目的。

创建一个自定义Repository方法,例如

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

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

}
Run Code Online (Sandbox Code Playgroud)

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;
 }
}
Run Code Online (Sandbox Code Playgroud)