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?
source
share