Google App Engine中一对多关系的分页 - JPA

时间:2013-02-19 00:57:26

标签: java google-app-engine jpa pagination

我在Google App Engine中有一对多的关系。我正在使用JPA

public class Profile {
    @OneToMany(targetEntity=Gift.class, mappedBy="user", fetch=FetchType.LAZY, cascade={CascadeType.PERSIST, CascadeType.REMOVE})
    @OrderBy("date DESC")
    private List<Gift> gift = null;

    ... 
}

public class Gift {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Key key;

    @ManyToOne(fetch=FetchType.LAZY, targetEntity=Profile.class)
    private Profile user = null;

    ... 
}

如何为儿童实体“礼物”添加分页?假设我必须首先返回第1至第10礼物,然后是第11至第20礼物。

目前,我已退回整个列表。

public List<Gift> listGift(String email) throws PersistenceException{
    EntityManager em = EMF.get().createEntityManager();
    EntityTransaction tx = null;
    List<Gift> list = null;

    try{
        tx = em.getTransaction();
        tx.begin();

        Profile user = em.find(Profile.class, email);
        list = new ArrayList<Gift>(user.getGift());

        tx.commit();
    }finally{
        try {
            if (tx != null && tx.isActive()) {
                tx.rollback();
            }
        } finally {
            em.close();
        }
    }

    return list;
}

1 个答案:

答案 0 :(得分:0)

试试这个

public List<Gift> listGift(String email,int p) throws PersistenceException{
    EntityManager em = EMF.get().createEntityManager();
    EntityTransaction tx = null;
    List<Gift> list = null;
    List pagedList = new ArrayList();
    int view=10;
    try{
        tx = em.getTransaction();
        tx.begin();

        Profile user = em.find(Profile.class, email);
        list = new ArrayList<Gift>(user.getGift());
        int begin=(p-1)*view;
        int end = p*view;
        if(end> list.size())
            end=list.size();
        for (int i=begin;i<end;i++){
            pagedList.add(list.get(i));
        }

        tx.commit();
    }finally{
        try {
            if (tx != null && tx.isActive()) {
                tx.rollback();
            }
        } finally {
            em.close();
        }
    }

    return pagedList;
}

通常我在我的控制器和视图层(使用jstl的jsp)中进行分页。但也许您的要求需要在DAO层中执行此操作。