简体   繁体   English

SQL 聚合 GROUP BY 和 COUNT 在 Spring JPA

[英]SQL aggregation GROUP BY and COUNT in Spring JPA

I have an SQL table:我有一张 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;
}

I want to get a count, grouping by country and state with the output class being List of Count:我想得到一个计数,按国家和 state 分组,其中 output class 是计数列表:

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

I know the query is我知道查询是

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

But I want to do this using JPA Specification.但我想使用 JPA 规范来做到这一点。 How can I achieve this using JPA Specification in spring boot?如何在 spring 引导中使用 JPA 规范来实现这一点?

You could achieve this by using Spring Data JPA Projections in Spring Data JPA.您可以通过使用Spring 数据 JPA Spring 数据 Z9CE3D1BD8890F50A0C4480936中的投影来实现此目的

Create a custom Repository method as创建一个自定义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();

}

Also you must define the specific constructor in Count class which will handle this projection您还必须在Count class 中定义特定的构造函数来处理这个投影

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;
 }
}

You can use JpaRepository interface.您可以使用 JpaRepository 接口。 Example:例子:

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

    public int countAllByCountryAndState(String countryName, String stateName);

}

And in your service:在您的服务中:

@Service
@Transactional
public class PopulationService {

    @Autowired
    private PopulationRepository populationRepository;

    public int countPopulationByCountryAndState(String countryName, String stateName) { 

         return populationRepository.countAllByCountryAndState(countryName, stateName);
    }

}  

Sorry, I made mistake it can be simpler.对不起,我弄错了它可以更简单。 I edited my code.我编辑了我的代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM