Java - Calculate How Many Elements have x property

user12361681 :

I have a very basic class:

@Entity
@Table(name = "ApplicationType")
public class ApplicationType {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long applicationTypeId;
    private String description;
    @OneToMany(mappedBy = "applicationType")
    private Set<Application> applications; 

   // getters setters
  }

And a Controller:

@GetMapping("/application/types")
public ResponseEntity<?> getApplicationTypes() {
    List<ApplicationType> applicationTypes = applicationTypeRepository.findAll();
    return new ResponseEntity<>(applicationTypes, HttpStatus.OK);
}

My DB has 100000 applications returned by findAll();, 50000 of applicationType 1 and 50000 of applicationType 2

How can I easily extract how many applications of each type exists without crashing my API? My solution was to loop all the applications and checking their type but this is VERY BAD

pero_hero :

You could use Spring Data (> 1.7.1) and in your CrudRepository<Application, "Primary ID Type of Application Table"> have a method like:

 Long countByApplicationType(String applicationType);

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=217273&siteId=1