I have two models: βBook and chapterβ in a one-to-many relationship. I manually create keys for both the book and the chapter. To continue, I create a book object, then add a copy of the chapter to it, and then save the book. This works great as I see them in the data store. Now, when I try to extract a chapter from the repository file, I get a null object.
Here's what the keys look like in the data warehouse:
Under Book: name/id = 123 chapters = [Book(123)/Chapter("abc")] Under Chapter: name/id = abc
I created my keys, both for creating and for creating objects using
Key key = KeyFactory.createKey(Chapter.class.getSimpleName(), chapterId);
My fetch code:
Key key = KeyFactory.createKey(Chapter.class.getSimpleName(), chapterId); Chapter chp = mgr.find(Chapter.class, key);//chp is always null (yes in debug mode as well)
UPDATE:
I am trying to do the same in a book and it works great. So the problem is the chapter. Perhaps this is because I saved the chapter through the book (but I see both in the data warehouse, as mentioned above).
So, the question arises: is there a way to get the section yourself (by its key), if so, please remove the code fragment.
Download Source Package UPDATE:
@Entity public class Book implements java.io.Serializable{ private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Key key; @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER) private List<Chapter> Chapters = new ArrayList<Chapter>(); public List<Chapter> getChapters() { return Chapters; } public void setChapters(List<Chapter> Chapters) { this.Chapters = Chapters; } public Book(long num, List<Chapter> Chapters) { super(); Key key = KeyFactory.createKey(Book.class.getSimpleName(), num); this.key = key; this.Chapters = Chapters; } public Book(long num) { super(); Key key = KeyFactory.createKey(Book.class.getSimpleName(), num); this.key = key; } public Book() { } public Key getKey() { return key; } public void setKey(Key key) { this.key = key; } } @Entity public class Chapter implements java.io.Serializable{ private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Key key; private String content; public Chapter(String ChapterId, String content) { super(); Key key = KeyFactory.createKey(Chapter.class.getSimpleName(), ChapterId); this.key = key; this.content = content; } public Key getKey() { return key; } public void setKey(Key key) { this.key = key; } public String getContent() { return content; } public void set content(String content) { this.content = content; } }
Code to add:
Book bk = new Book(num); Chapter chp = new Chapter(ChapterId, content); bk.getChapters().add(chp); bookDao.put(bk); mgr.persist(bk);