JPA OneToMany - null collection

I am trying to set up bidirectional relationships using JPA. I understand that this is the responsibility of the application to maintain both sides of the relationship.

For example, a library has several books. In the library object, I:

@Entity
public class Library {
  ..
  @OneToMany(mappedBy = "library", cascade = CascadeType.ALL)
  private Collection<Book> books;

  public void addBook(Book b) {
    this.books.add(b);
    if(b.getLibrary() != this)
      b.setLibrary(this);
  }
  ..
}

Book Object:

@Entity
public class Book {
  ..
  @ManyToOne
  @JoinColumn(name = "LibraryId")
  private Library library;

  public void setLibrary(Library l) {
    this.library = l;
    if(!this.library.getBooks().contains(this))
      this.library.getBooks().add(this);
  }
  ..
}

Unfortunately, the collection on the OneToMany side is NULL. So, for example, the setLibrary () call fails because this.library.getBooks () contains (this) throws a NullPointerException.

Is this normal behavior? Do I have to instantiate the collection myself (which seems a little strange) or are there other solutions?

+4
source share
3 answers

- Java. Java , @Entity.

, , .

, , , .

( em.find(), ), , JPA .

+6

, Collection . ;

, addBook . NullPointerException.

@OneToMany(mappedBy = "library", cascade = CascadeType.ALL)
 private Collection<Book> books;

 public void addBook(Book b) {
    this.books.add(b);
    if(b.getLibrary() != this)
    b.setLibrary(this);
 }

.

private Collection<Book> books;

private Collection<Book> books = new ArrayList<Book>();
+6

Try setting the association type property to the OneToMany side. Indeed, you can leave this part (this.library.getBooks (). Add (this)), which will be recorded during the session:

Library l = new Library();    
Book b = new Book();
b.setLibrary(l);
l.getBooks().add(b);
+1
source

All Articles