简体   繁体   English

使用jpa持久化(或查找)对象不会保存它封装的对象列表

[英]Persist (or find) an object with jpa does not save the list of object that it encapsulates

Suppose that we have in a relational database a table "Book" that is referenced by a table "Page". 假设我们在关系数据库中有一个由表“Page”引用的表“Book”。 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 在JPA中,此关系在实体类中定义如下

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. 现在,如果我创建一个Book实例,并使用一个Page实体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. 这可以自动完成,即如果我保存书籍,同时书中包含的页面也保存在Page表中。

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. 同样的问题是检索一本书,逻辑上当我拿到一本书(使用jpa find方法)并且它封装了一个页面列表,我必须在书籍实例中有相关的页面,但事实并非如此。

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) . 您需要添加@OneToMany(mappedBy = "book", cascade = CascadeType.PERSIST) For JPA's OneToMany , by default no operations are Cascaded . 对于JPA的OneToMany ,默认情况下没有任何操作是Cascaded

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM