0

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

1 回答 1

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 层执行此操作。

于 2013-04-26T02:27:13.300 回答