【问题标题】:SQL aggregation GROUP BY and COUNT in Spring JPASpring JPA 中的 SQL 聚合 GROUP BY 和 COUNT
【发布时间】:2020-08-07 05:10:00
【问题描述】:

我有一个 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;
}

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

  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 规范来做到这一点。如何在 Spring Boot 中使用 JPA 规范来实现这一点?

【问题讨论】:

标签: java sql sql-server spring-boot jpa


【解决方案1】:

您可以通过在 Spring Data JPA 中使用 Spring Data 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;
 }
}

【讨论】:

    【解决方案2】:

    您可以使用 JpaRepository 接口。 示例:

    @Repository
    public interface PopulationRepository extends JpaRepository<Population, Long> {
    
        public int countAllByCountryAndState(String countryName, String stateName);
    
    }
    

    为您服务:

    @Service
    @Transactional
    public class PopulationService {
    
        @Autowired
        private PopulationRepository populationRepository;
    
        public int countPopulationByCountryAndState(String countryName, String stateName) { 
    
             return populationRepository.countAllByCountryAndState(countryName, stateName);
        }
    
    }  
    

    对不起,我弄错了它可以更简单。我编辑了我的代码。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-02-25
      • 1970-01-01
      • 2014-12-27
      • 1970-01-01
      • 1970-01-01
      • 2018-06-27
      • 1970-01-01
      • 2021-04-01
      相关资源
      最近更新 更多