日期:2014-05-20  浏览次数:20737 次

大数据量下的JPA分页问题。
jpa使用toplink实现。数据表有200多万的记录。 一运行下面的分页查询就出现这个错误:
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
at com.mysql.jdbc.MysqlIO.reuseAndReadPacket(MysqlIO.java:2931)
at com.mysql.jdbc.MysqlIO.reuseAndReadPacket(MysqlIO.java:2871)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3414)

代码:

public class PagingTest {
EntityManagerFactory emf = null;  
  private javax.persistence.EntityManager em;
/**
* @param args
*/
public static void main(String[] args) {
PagingTest pTest= new PagingTest();
pTest.testPaging();
 
}
public void testPaging(){
emf = EntityManagerHelper.getEmf();
em= emf.createEntityManager();
Query rowCountQuery = em.createQuery("SELECT COUNT(c) FROM Customer c"); // NOI18N
int size =((Long) rowCountQuery.getSingleResult()).intValue();
System.out.println(size);
final Query getRowsQuery = em.createQuery("select c from Customer c");
  System.out.println("numer of requests to the database " + counter++);
  Query query = getRowsQuery.setMaxResults(20).setFirstResult(1000000);//这里如果设置为setFirstResult(100000); 就可以运行。
   
  //add the cache
  List<Customer> resultList = query.getResultList();
  System.out.println("=====query done " );
  for(Customer cust:resultList){
  System.out.println("cust:"+cust.getCustomerId()+","+cust.getCustomerName());
  }
}

  private javax.persistence.EntityManager entityManager1;
  private javax.persistence.Query getRowsQuery;
  private javax.persistence.Query rowCountQuery;
   
  private List<Customer> getList() {
  getRowsQuery = java.beans.Beans.isDesignTime() ? null : entityManager1.createQuery("SELECT c FROM Customer c"); // NOI18N
  rowCountQuery = java.beans.Beans.isDesignTime() ? null : entityManager1.createQuery("SELECT COUNT(c) FROM Customer c"); // NOI18N

  List<Customer> toReturn = new ResultListJPA<Customer>(rowCountQuery, getRowsQuery);
  return toReturn;
  }
   
  private int counter=0;
   
}

请问高手怎么解决这个问题?

------解决方案--------------------
按需查找