1

I am trying to print info about every user in my Mysql DB. I use function findAll() in Repository interface, but I am getting Null Pointer Exception.

Here is my Repository interface:

@Repository
    public interface UserRepository extends CrudRepository<User, Long> {
    User findOneByUsername(String username);
    List<User> findAll();
}

Here is my Controller

@GetMapping("/admin/allUsers")
    public String getAllUsers(Model model) {
    model.addAttribute("users",this.userRepository.findAll());
    return "admin/allUsers";
}

I am getting Null Pointer Exception at the row where excecute model.addAtribute(...)

Thanks in advance!

Innat
  • 16,113
  • 6
  • 53
  • 101
Iliqn Tachev
  • 31
  • 1
  • 7
  • Possible duplicate of [What is a NullPointerException, and how do I fix it?](https://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – Logan May 24 '18 at 21:23
  • how you have initialized `userRepository` in your `Controller`? – Amit K Bist May 24 '18 at 22:01

2 Answers2

4

You need to Autowire userRepository or make it a bean itself on the config class. After that, make sure is not a static field. I believe Spring does not autowire static fields.

Source.

Cempoalxóchitl
  • 176
  • 3
  • 15
0

in controller

@Autowired
UserRepository userRepository;
benderalex5
  • 129
  • 1
  • 3