Suppose that we have in a relational database a table "Book" that is referenced by a table "Page". A book contains one or more pages and a page belongs to a single book.
In JPA this relation is defined as below in the entities classes
class Book:
@OneToMany(mappedBy = "book")
private List<Page> pageList;
class Page:
@JoinColumn(name = "book", referencedColumnName = "id")
@ManyToOne
private Book book;
Now, if I create a Book instance and I set its list of pages with a list of Page entities objets. When I persist the book (see code below), I find that the book is stored in the table Book but the book pages are not saved. Can this be done automatically, ie if I save a book while the pages contained in the book are also saved in the Page table.
Same question for the retrieval of a book, logically when I get a book (use jpa find method) and it encapsulate a list of pages I must have the associated pages in the book instance, but this is not the case.
So what is my fault? or what I'm missing ?
public void add(Book book) throws TestException
{
try {
em = getEmf().createEntityManager();
EntityTransaction tr = em.getTransaction();
tr.begin();
em.persist(book);
tr.commit();
em.close();
} catch (PersistenceException pex) {
throw new TestException(
"This book already exists.", pex);
}
}
You need to add @OneToMany(mappedBy = "book", cascade = CascadeType.PERSIST)
. For JPA's OneToMany
, by default no operations are Cascaded .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.