I want to map a list of Race into list of RaceDto. When I try to map it, I get an error: Non-static method cannot be referenced from a static context
RaceRepository.java
@Repository
public interface RaceRepository extends CrudRepository<Race, Long> {
List<Race> findAll();
// ...
}
RaceDtoMapper.java
@Service
public class RaceDtoMapper {
RaceDto map(Race race){
RaceDto dto = new RaceDto();
dto.setId(race.getId());
dto.setMaxPlayers(race.getMaxPlayers());
dto.setDescription(race.getDescription());
dto.setLocation(race.getLocation());
dto.setDate(race.getDate());
dto.setState(race.getState());
dto.setRaceEventId(race.getRaceEvent().getId());
return(dto);
}
}
RaceService.java
@Service
public class RaceService {
private final RaceRepository raceRepository;
private final RaceDtoMapper raceDtoMapper;
private final RacePersonDtoMapper racePersonDtoMapper;
public RaceService(RaceRepository raceRepository, RaceDtoMapper raceDtoMapper, RacePersonDtoMapper racePersonDtoMapper) {
this.raceRepository = raceRepository;
this.raceDtoMapper = raceDtoMapper;
this.racePersonDtoMapper = racePersonDtoMapper;
}
List<RaceDto> getRaces(){
return raceRepository.findAll()
.stream()
.map(RaceDtoMapper::map) // HERE IS THE CODE CAUSING THE ERROR
.toList();
}
// ...
}
You are referring to the method map
while there's no instance of it.
Either make the method static:
static RaceDto map(Race race){
Or create an instance:
List<RaceDto> getRaces(){
RaceDtoMapper raceDtoMapper = new RaceDtoMapper();
return raceRepository.findAll()
.stream()
.map(raceDtoMapper::map) // use instance
.toList();
}