我正在尝试使用JPA建立双向关系.我理解应用程序的责任是维护关系的双方.
例如,图书馆有多本图书.在图书馆实体我有:
@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);
}
..
}
Run Code Online (Sandbox Code Playgroud)
图书实体是:
@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);
}
..
}
Run Code Online (Sandbox Code Playgroud)
不幸的是,OneToMany端的集合为空.因此,例如,对setLibrary()的调用失败,因为this.library.getBooks().contains(this)会导致NullPointerException.
这是正常的行为吗?我应该自己实例化这个集合(这看起来有点奇怪),还是有其他解决方案?