FootballResultSaveOrUpdateHelper.java
package com.mojosoft.demo.repository;
import com.mojosoft.demo.cache.MatchKey;
import com.mojosoft.demo.dto.FootballResultDTO;
import com.mojosoft.demo.entity.FootballResult;
import com.mojosoft.demo.mapper.MapperHelper;
import jakarta.transaction.Transactional;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
/**
* This class is responsible for saving or updating football results.
*/
@Service
@AllArgsConstructor
@SuppressWarnings("checkstyle:AbbreviationAsWordInName")
public class FootballResultSaveOrUpdateHelper {
private final FootballResultRepository footballResultRepository;
private final MapperHelper mapperHelper;
/**
* This method saves the football result.
*
* @param key the key
* @param value the value
*/
@Transactional
public void save(MatchKey key, FootballResultDTO value) {
Optional<FootballResult> entity = getSaveEntity(key, value);
entity.ifPresent(footballResultRepository::save);
}
/**
* This method saves the football results.
*
* @param footballResultDTOS the football results
*/
@Transactional
public List<FootballResultDTO> saveAll(List<FootballResultDTO> footballResultDTOS) {
if (footballResultDTOS == null || footballResultDTOS.isEmpty()) {
return List.of();
}
List<FootballResult> entitiesToSave = new ArrayList<>();
footballResultDTOS.forEach((value) -> {
Optional<FootballResult> entity =
getSaveEntity(MatchKey.createMatchKey(value), value);
entity.ifPresent(entitiesToSave::add);
});
if (!entitiesToSave.isEmpty()) {
footballResultRepository.saveAll(entitiesToSave);
}
return entitiesToSave.stream()
.map(mapperHelper::footballResultToDto)
.collect(Collectors.toList());
}
/**
* Returns an {@link Optional} of {@link FootballResult} entity to save.
*
* @param matchKey the match key
* @param value the value
* @return an {@link Optional} of {@link FootballResult} entity to save
*/
private Optional<FootballResult> getSaveEntity(MatchKey matchKey, FootballResultDTO value) {
Optional<FootballResult> existingResult = footballResultRepository
.findBySeasonAndHomeTeamAndAwayTeam(
matchKey.season(), matchKey.homeTeam(), matchKey.awayTeam());
if (existingResult.isPresent()) {
FootballResult existingEntity = existingResult.get();
if (!mapperHelper.isEqual(value, existingEntity)) {
mapperHelper.updateFootballResultEntityFromDto(value, existingEntity);
return Optional.of(existingEntity);
}
} else {
FootballResult newEntity = mapperHelper.footballResultToEntity(value);
return Optional.of(newEntity);
}
return Optional.empty();
}
}