I have this repository interface:
public interface ScoreCardRepository extends CrudRepository<ScoreCard, Long> {
@Query(value = "SELECT SUM(SCORE) FROM SCORE_CARD WHERE USER_ID = :userId", nativeQuery = true)
Integer getTotalScoreForUser(Long userId);
}
and this controller:
@RestController
@RequestMapping("/gamification")
public class GamificationController {
private final LeaderBoardServiceImpl leaderBoardService;
private final GameServiceImpl gameService;
@Autowired
public GamificationController(GameServiceImpl gameService, LeaderBoardServiceImpl leaderBoardService){
this.gameService = gameService;
this.leaderBoardService = leaderBoardService;
}
@GetMapping("/retrieve-stats")
ResponseEntity<GameStats> getUserStats(@RequestParam("user") String userId){
return ResponseEntity.ok(gameService.retrieveStatsForUser(Long.parseLong(userId)));
}
}
Now, when I call the /retrieve-stats
and we go inside gameService.retrieveStatsForUser
I get a null pointer exception
@Service
public class GameServiceImpl implements GameService {
private final ScoreCardRepository scoreCardRepository;
private final BadgeCardRepository badgeCardRepository;
@Autowired
public GameServiceImpl(ScoreCardRepository scoreCardRepository, BadgeCardRepository badgeCardRepository) {
this.scoreCardRepository = scoreCardRepository;
this.badgeCardRepository = badgeCardRepository;
}
@Override
public GameStats retrieveStatsForUser(Long userId) {
List<BadgeCard> badgeCardList = badgeCardRepository.findByUserIdOrderByBadgeTimestampDesc(userId);
--->>> int totalScore = scoreCardRepository.getTotalScoreForUser(userId); //NULL POINTER EXCEPTION
GameStats gameStats = new GameStats(userId, totalScore,
badgeCardList.stream().map(BadgeCard::getBadge).collect(Collectors.toList()));
return gameStats;
}
}
Does this mean that the scoreCardRepository
bean doesn't get instantiated? That should happen in the @Autowired GamificationserviceImpl
constructor right? the badgeCardRepository
gets instantiated fine. What's happening?
CodePudding user response:
I suggest another cause:
Integer getTotalScoreForUser(Long userId);
This method can return in Integer of null
which causes a NPE during auto-boxing to primitive datatype int at
int totalScore = scoreCardRepository.getTotalScoreForUser(userId);