0

I am currently trying to add some Roles to my User, however I always get a NullPointerException when I try to do so.

This is my AppUser with the addRole method where the exception happens

@Builder
@AllArgsConstructor
@NoArgsConstructor
@Getter
@Setter
@Entity
public class AppUser {
    @Id
    @SequenceGenerator(
            name = "app_user_id_sequence",
            sequenceName = "app_user_id_sequence"
    )
    @GeneratedValue(
            strategy = GenerationType.SEQUENCE,
            generator = "app_user_id_sequence"
    )
    private Long id;
    @NotBlank
    @Column(nullable = false)
    private String firstName;

    @NotBlank
    @Column(nullable = false)
    private String lastName;

    @Email
    @Column(nullable = false, unique = true)
    private String email;

    @NotBlank
    @Column(nullable = false)
    private String password;

    @ManyToMany(cascade = {CascadeType.PERSIST, CascadeType.MERGE})
    @JoinTable(name = "app_user_roles",
            joinColumns = @JoinColumn(name = "app_user_id"),
            inverseJoinColumns = @JoinColumn(name = "roles_id"))
    private Collection<Role> roles = new ArrayList<>();

    public void addRole (Role role) {
            roles.add(role);
    }
}

And this is the place where I am adding a role to my user

@Component
public class UserSeeder implements CommandLineRunner {
    @Autowired
    private AppUserRepository appUserRepository;
    @Autowired
    private RoleRepository roleRepository;
    private Faker faker = new Faker();

    @Override
    public void run(String... args) throws Exception {
        loadUserData();
    }

    private void loadUserData() {
        if (appUserRepository.count() == 0) {

            roleRepository.findAll().stream().forEach(role -> {
                AppUser appUser = AppUser.builder()
                        .firstName(faker.name().firstName())
                        .lastName(faker.name().lastName())
                        .email(faker.internet().emailAddress())
                        .password("password")
                        .build();
                
                appUser.addRole(role); //Adding the role here
                
                appUserRepository.save(appUser);
            });
        }
    }
}

The error I am getting

java.lang.IllegalStateException: Failed to execute CommandLineRunner
    at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:774) ~[spring-boot-2.7.1.jar:2.7.1]
    at org.springframework.boot.SpringApplication.callRunners(SpringApplication.java:755) ~[spring-boot-2.7.1.jar:2.7.1]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:315) ~[spring-boot-2.7.1.jar:2.7.1]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1306) ~[spring-boot-2.7.1.jar:2.7.1]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1295) ~[spring-boot-2.7.1.jar:2.7.1]
    at com.alex.user.UserApplication.main(UserApplication.java:11) ~[classes/:na]
Caused by: java.lang.NullPointerException: Cannot invoke "java.util.Collection.add(Object)" because "this.roles" is null
    at com.alex.user.AppUser.addRole(AppUser.java:51) ~[classes/:na]
    at com.alex.user.seeders.UserSeeder.lambda$loadUserData$0(UserSeeder.java:43) ~[classes/:na]
    at java.base/java.util.ArrayList$ArrayListSpliterator.forEachRemaining(ArrayList.java:1625) ~[na:na]
    at java.base/java.util.stream.ReferencePipeline$Head.forEach(ReferencePipeline.java:762) ~[na:na]
    at com.alex.user.seeders.UserSeeder.loadUserData(UserSeeder.java:35) ~[classes/:na]
    at com.alex.user.seeders.UserSeeder.run(UserSeeder.java:29) ~[classes/:na]
    at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:771) ~[spring-boot-2.7.1.jar:2.7.1]

  • 3
    Did you try to annotate your list with Lombok's annotation `@Builder.Default`? – 0x1C1B Jun 30 '22 at 10:50
  • 1
    The list is not initialized in the builder, so it is set to null when you create the object, overwriting the list instance with null. When Java tells you something is null, believe it. – Mark Rotteveel Jun 30 '22 at 10:59
  • @0x1C1B Now for some reason works. Do you have any idea why I got that NullPointerException ? Pretty weird considering that it is instantiated –  Jun 30 '22 at 11:00
  • @MarkRotteveel Ohh I didn't know that about the builder. Thanks a lot! –  Jun 30 '22 at 11:01

0 Answers0