【问题标题】:trouble getting one-to-many relationship to work on app-engine and JPA难以在应用程序引擎和 JPA 上建立一对多关系
【发布时间】:2013-04-06 10:36:50
【问题描述】:

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

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.

经过大量研究,我终于找到了一个博客,上面写着只需将@Basic 放在getChapters 方法上。当我这样做时,我收到了这个新错误:

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;
}

【问题讨论】:

标签: google-app-engine google-cloud-datastore datanucleus gae-eclipse-plugin


【解决方案1】:

您需要在 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;
}

Here is the description of all the cascade types.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-04-24
    • 1970-01-01
    • 2011-12-16
    • 1970-01-01
    • 2012-07-15
    • 2011-06-19
    • 1970-01-01
    相关资源
    最近更新 更多