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

后端 未结 15 2566
攒了一身酷
攒了一身酷 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条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-27 10:34

    An Example with JPA and NativeQuery fetching everytime the size Elements using offsets

    public List getXByFetching(int fetchSize) {
            int totalX = getTotalRows(Entity);
            List result = new ArrayList<>();
            for (int offset = 0; offset < totalX; offset = offset + fetchSize) {
                EntityManager entityManager = getEntityManager();
                String sql = getSqlSelect(Entity) + " OFFSET " + offset + " ROWS";
                Query query = entityManager.createNativeQuery(sql, X.class);
                query.setMaxResults(fetchSize);
                result.addAll(query.getResultList());
                entityManager.flush();
                entityManager.clear();
            return result;
        }
    

提交回复
热议问题