Reputation: 11780
I have a one-to-many relationship between Book and Chapter. I am able to create a book object and add chapters to it successfully (I look in the datastore and see my creation). However, after a fetch a book if I try to loop through the chapters, I get the error
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.
After much research, I finally found a blog that says just place @Basic
on the getChapters
method. When I do that, I get this new error:
java.lang.IllegalStateException: Field "Book.chapters" contains a persistable object
that isnt persistent, but the field doesnt allow cascade-persist!
I have been trying all sorts of things, the latest look of the models is
@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;
}
Upvotes: 0
Views: 485
Reputation: 792
You need to declare the cascade type on your Book attribute, so that JPA knows what to do when performing operations on your Chapter entity.
@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.
Upvotes: 0