i am new to CompletableFutures and need some to help better understand this topic. Trying to implement a personal project where i write a service to read some data from the mysql sakila db. Here is the db schema : enter link description here
Here is what i am trying to achieve :
1.) CompletableFuture to Load a Film object by id. 2.) If it doesnt exist then dont proceed. 3.) If it exists then load : Categories , Languages in parallel and update Category Names and Language Name in the Film object returned at 1.)
While i can do it using thenApply , i would ideally like to load : the filmCategories ,categories and languages in parallel and then merge the data into my dto.
Any help would be appreciated
CompletableFuture<Map<Integer,String>> categories = CompletableFuture.supplyAsync(
() -> categoryService.getCategories().stream()
.collect(Collectors.toMap(CategoryDto::getCategoryId,CategoryDto::getCategoryName))
) ;
CompletableFuture<Map<Integer,String>> languages = CompletableFuture.supplyAsync(
() -> languageService.getLanguages().stream()
.collect(Collectors.toMap(LanguageDto::getLanguageId,LanguageDto::getLanguageName))
) ;
CompletableFuture<Map<Integer,List<FilmCategoryDto>>> filmCategories = CompletableFuture.supplyAsync(
() -> filmCategoryRepository.findFilmCategoryEntitiesByFilmId(filmId)
.stream().map(
e -> {
FilmCategoryDto filmCategoryDto = mapper.filmCategoryToFilmCategoryDto(e);
filmCategoryDto.setCategoryName(categories.join().get(filmCategoryDto.getCategoryId()));
return filmCategoryDto;
}
)
.collect(Collectors.groupingBy(FilmCategoryDto::getFilmId))
) ;
CompletableFuture.allOf(filmCategories,languages).join();
return filmRepository.findById(filmId)
.map(e -> {
FilmDto f = mapper.filmToFilmDto(e);
f.setLanguageName(languages.join().get(f.getLanguageId()));
f.setFilmCategories(filmCategories.join().get(f.getFilmId()));
return f;
})
.orElse(null);