Comics 对象可以有多个 Chapter 对象。
我在Comics
课堂上有这个:
@OneToMany(targetEntity=Chapter.class, mappedBy="comics", fetch=FetchType.LAZY, cascade={CascadeType.PERSIST, CascadeType.REMOVE})
private List<Chapter> chapters = null;
我在漫画中添加章节的方法:
public Chapter addChapter(Chapter chapter, String key) {
EntityManager em = EMF.get().createEntityManager();
EntityTransaction tx = null;
Comics comics = null;
try{
tx = em.getTransaction();
tx.begin();
comics = em.find(Comics.class, KeyFactory.stringToKey(key));
chapter.setPages( new LinkedList<Page>() );
comics.getChapters().add(chapter);
tx.commit();
}catch(Exception ex){
ex.printStackTrace();
if(tx != null && tx.isActive())
tx.rollback();
} finally{
em.close();
}
return chapter;
}
我看漫画的方法:
public Comics read(String key) throws IllegalAccessException, InvocationTargetException{
EntityManager em = EMF.get().createEntityManager();
Comics comics = new Comics();
try{
Comics emComics = em.find(Comics.class, KeyFactory.stringToKey(key));
BeanUtils.copyProperties(comics, emComics);
comics.setChapters(new LinkedList<Chapter> (emComics.getChapters()));
}finally{
em.close();
}
return comics;
}
当我保存 newComics
时,我还有:
comics.setChapters( new LinkedList<Chapter>() );
问题是该read
方法返回意外的chapters
. chapters
按顺序显示的最佳方法是什么?