0

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按顺序显示的最佳方法是什么?

4

1 回答 1

1

您可以使用@OrderBy注释:

例如:

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

这是假设有一个可比较的chapterNumber字段

于 2012-09-21T02:53:39.830 回答