JPA OneToMany - Collection is null

前端 未结 3 1076
长发绾君心
长发绾君心 2021-01-13 06:52

I\'m trying to set up a bidirectional relationship using JPA. I understand that it\'s the responsability of the application to maintain both sides of the relationship.

3条回答
  •  有刺的猬
    2021-01-13 07:10

    It seems that books type of Collection in Library class is not initilized. It is null;

    So when class addBook method to add a book object to collection. It cause NullPointerException.

    @OneToMany(mappedBy = "library", cascade = CascadeType.ALL)
     private Collection books;
    
     public void addBook(Book b) {
        this.books.add(b);
        if(b.getLibrary() != this)
        b.setLibrary(this);
     }
    

    Initilize it and have a try.

    Change

    private Collection books;
    

    To

    private Collection books = new ArrayList();
    

提交回复
热议问题