Reputation: 17269
Comics object can have many Chapter object.
I have this in Comics
class:
@OneToMany(targetEntity=Chapter.class, mappedBy="comics", fetch=FetchType.LAZY, cascade={CascadeType.PERSIST, CascadeType.REMOVE})
private List<Chapter> chapters = null;
My method in adding a chapter to a Comics:
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;
}
My method for reading a Comics:
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;
}
When I saved new Comics
, I also have:
comics.setChapters( new LinkedList<Chapter>() );
The problem is that read
method return unexpected ordering of chapters
. What would be the best approach to display chapters
in order?
Upvotes: 0
Views: 340
Reputation: 9331
You can use @OrderBy annotation:
For example:
@OneToMany(targetEntity=Chapter.class, mappedBy="comics", fetch=FetchType.LAZY, cascade={CascadeType.PERSIST, CascadeType.REMOVE})
@OrderBy("chapterNumber")
private List<Chapter> chapters = null;
This is assuming there is a chapterNumber field which is comparable
Upvotes: 1