漫画对象可以有许多章对象。

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


保存新的Comics时,我还有:

comics.setChapters( new LinkedList<Chapter>() );


问题是read方法返回chapters的意外顺序。依次显示chapters的最佳方法是什么?

最佳答案

您可以使用@OrderBy批注:

例如:

@OneToMany(targetEntity=Chapter.class, mappedBy="comics", fetch=FetchType.LAZY, cascade={CascadeType.PERSIST, CascadeType.REMOVE})
@OrderBy("chapterNumber")
private List<Chapter> chapters = null;


假设存在一个可比较的ChapterNumber字段

关于java - Google App Engine中的订购列表-JPA,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12523017/

10-10 02:03