JPA: what is the proper pattern for iterating over large result sets?

后端 未结 15 2585
攒了一身酷
攒了一身酷 2020-11-27 09:50

Let\'s say I have a table with millions of rows. Using JPA, what\'s the proper way to iterate over a query against that table, such that I don\'t have all an in-memo

15条回答
  •  旧时难觅i
    2020-11-27 10:20

    If you use EclipseLink I' using this method to get result as Iterable

    private static  Iterable getResult(TypedQuery query)
    {
      //eclipseLink
      if(query instanceof JpaQuery) {
        JpaQuery jQuery = (JpaQuery) query;
        jQuery.setHint(QueryHints.RESULT_SET_TYPE, ResultSetType.ForwardOnly)
           .setHint(QueryHints.SCROLLABLE_CURSOR, true);
    
        final Cursor cursor = jQuery.getResultCursor();
        return new Iterable()
        {     
          @SuppressWarnings("unchecked")
          @Override
          public Iterator iterator()
          {
            return cursor;
          }
        }; 
       }
      return query.getResultList();  
    }  
    

    close Method

    static void closeCursor(Iterable list)
    {
      if (list.iterator() instanceof Cursor)
        {
          ((Cursor) list.iterator()).close();
        }
    }
    

提交回复
热议问题