2013-02-19 39 views
0

我在Google App Engine中擁有一對多關係。即時通訊使用JPAGoogle 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; 
} 

回答

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

通常我讓尋呼在我的控制器和視圖層(JSP使用JSTL)。但是,也許你的需求需要在DAO層做到這一點。

相關問題