0

我在书和章节之间有一对多的关系。我能够创建一个书籍对象并成功为其添加章节(我查看数据存储并查看我的创建)。但是,如果我尝试循环浏览这些章节,在取一本书后,我会收到错误消息

javax.jdo.JDODetachedFieldAccessException: You have just attempted to access field
"chapters" yet this field was not detached when you detached the object. Either dont
access this field, or detach it when detaching the object.

经过大量研究,我终于找到了一个博客,上面写着just place @Basicon the getChaptersmethod。当我这样做时,我收到了这个新错误:

java.lang.IllegalStateException: Field "Book.chapters" contains a persistable object
that isnt persistent, but the field doesnt allow cascade-persist!

我一直在尝试各种东西,模型的最新外观是

@Entity
public class Account {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Key key;

    @OneToMany(mappedBy = "book", cascade = CascadeType.ALL)
    private List<Chapter> chapters = new ArrayList<Chapter>();
}


@Entity
public class Chapter {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Key key;

    @ManyToOne(fetch = FetchType.EAGER)//already tried without annotation and with FetchType.LAZY
    private Book book;
}
4

1 回答 1

0

您需要在 Book 属性上声明级联类型,以便 JPA 在对 Chapter 实体执行操作时知道要做什么。

@Entity
public class Chapter {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Key key;

    @ManyToOne(cascade = CascadeType.ALL) // you can also add fetch type if needed
    private Book book;
}

这是所有级联类型的描述

于 2013-12-25T12:02:30.207 回答