Spring data JPA @Query mapping with named columns

后端 未结 1 1409
渐次进展
渐次进展 2021-01-27 08:24

I use Spring Boot 1.5 and spring data JPA with MySQL. I tried to run a simple counting query on a single table, but could not find a better way to map the Query results than thi

相关标签:
1条回答
  • 2021-01-27 09:09

    How about using Projections as below?

    static interface VehicleStats { 
        public String getSourceModule();
        public Long getVehicleCount();
    }
    

    And your repository method would be

    @Query("select v.sourceModule as sourceModule, count(v) as vehicleCount from Vehicle v group by v.sourceModule")
    List<VehicleStats> sourceModuleStats();
    

    In your Service class, you can use the interface methods as below.

    List<VehicleStats> objects = vehicleRepository.sourceModuleStats();
    return objects.stream()
            .map(o->SourceModuleStatDTO.from(getSourceModule(),getVehicleCount() )
            .collect(Collectors.toList());
    
    0 讨论(0)
提交回复
热议问题