java Spring JPA中的SQL聚合GROUP BY和COUNT

h6my8fg2  于 2022-12-25  发布在  Java
关注(0)|答案(2)|浏览(274)

我有一个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规范来做这件事,我怎么能在 Spring Boot 中用JPA规范来实现呢?

oymdgrw7

oymdgrw71#

您可以通过在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();

}

此外,您还必须在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;
 }
}
wfsdck30

wfsdck302#

您可以使用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);
    }

}

对不起,我犯了个错误,它可以更简单.我编辑了我的代码.

相关问题