【问题标题】:Pagination for One to Many Relationship in Google App Engine - JPAGoogle App Engine 中一对多关系的分页 - JPA
【发布时间】:2013-02-19 00:57:25
【问题描述】:

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

【问题讨论】:

    标签: java google-app-engine jpa pagination


    【解决方案1】:

    试试这个

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-19
      • 2011-03-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多