0

Hi guys im trying to get back to coding after a long break and im running into some problems. Im building a program which has a library of user uploaded books(not really uploading anything) and im running into an

Exception in thread "main" java.lang.NullPointerException
    at Library.beans.User.uploadBook(User.java:107)
    at Library.LibraryApplication.main(LibraryApplication.java:22)

when im trying to add a new book via a user.Im using spring btw.

coding snippets

User bean
@Entity
@Table(name = "Users")
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;
    @Column(nullable = false, unique = true)
    private String email;
    @Column(nullable = false)
    private String password;
    @Column(nullable = false, unique = true)
    private String userName;
//  ** Books added to a user private library **
    @ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    private List<Book> userLibrary;
//  ** Books uploaded by user **
    @OneToMany(cascade = CascadeType.ALL)
    private List<Book> userBooks;

    public User(String email, String password, String name) {
        super();
        this.email = email;
        this.password = password;
        this.userName = name;
    }
public void uploadBook(Book book) {
        this.userBooks.add(book);
    }

Book bean

@Entity
@Table(name = "Books")
public class Book {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;
    @Column(nullable = false)
    private String name;
    @Column(nullable = false)
    private String synopsis;
    @Column
    private String image;
    @Column
    private double rating;
    @Column
    private GenreType genre;
    @ManyToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    private User author;
    @OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    private List<Review> reviews;

The code in main which causes the exception

User user = new User("admin", "admin", "user1");

user.uploadBook(new Book("book1", "a", "b", GenreType.Action));

Extra notes If i creat a book outside a user by (book new book) and add an author to the ctr it works one way,the book will state its author is the "user" i inputed on creation but the same "user" wont have it listed under his uploaded books list. what am i missing here?

1 Answers1

-1

You have to initialize private List<Book> userBooks; in your User bean

Your list object is null which causes the NullPointerException when you are adding and object to this list.

This should solve your problem:

private List<Book> userBooks = new ArrayList();
famabenda
  • 48
  • 1
  • 9
  • Well..its workes...But why would i need to initialize inside my bean? i checked an old project i made which also has a list inside the bean and it worked fine without initializing it. – JavaNewbies May 06 '20 at 15:46