Service example

@Service
public class PlayerService {

    private final PlayerRepository playerRepository;

    private final AwardRepository awardRepository;

    private final TeamRepository teamRepository;

    @Autowired
    public PlayerService(PlayerRepository playerRepository, AwardRepository awardRepository, TeamRepository teamRepository) {
        this.playerRepository = playerRepository;
        this.awardRepository = awardRepository;
        this.teamRepository = teamRepository;
    }

    public List<Player> findAll() {
        return playerRepository.findAll();
    }

    public Optional<Player> findById(Long id){
        return playerRepository.findById(id);
    }

    public Player save(Player player) {

        // If we are cascading/persisting new received awards, we need to fetch the award from the database
        if(player.getReceivedAwards() != null){
            player.getReceivedAwards().forEach(awardReceived -> {
                Optional<Award> award = awardRepository.findById(awardReceived.getAward().getId());
                award.ifPresent(awardReceived::setAward);
                awardReceived.setPlayer(player);
            });
        }

        // If we are cascading/persisting teams played for, we need to fetch the teams from the database
        if(player.getTeamsPlayedFor() != null){
            for(int i = 0; i < player.getTeamsPlayedFor().size(); i++){
                Team team = player.getTeamsPlayedFor().get(i);
                Optional<Team> teamFromDb = teamRepository.findById(team.getId());

                int finalI = i;
                teamFromDb.ifPresent(fetchedTeam -> player.getTeamsPlayedFor().set(finalI, fetchedTeam));
            }
        }

        return playerRepository.save(player);
    }

    public Player patch(Player existingPlayer, Map<String, Object> updates){
        for (Map.Entry<String, Object> entry : updates.entrySet()) {
            switch (entry.getKey()) {
                case "firstName":
                    existingPlayer.setFirstName((String) entry.getValue());
                    break;
                case "lastName":
                    existingPlayer.setLastName((String) entry.getValue());
                    break;
                case "position":
                    existingPlayer.setPosition((Position) entry.getValue());
                    break;
                case "team":
                    existingPlayer.setTeam((Team) entry.getValue());
                    break;
                case "franchiseTagged":
                    existingPlayer.setFranchiseTagged((Boolean) entry.getValue());
                    break;
            }
        }

        return playerRepository.save(existingPlayer);
    }

    public void deleteById(Long id){
        playerRepository.deleteById(id);
    }
}