简体   繁体   English

在列表中生成大量数据并生成文件

[英]Generate a lot of data in a list and generate the file

I have a table in the database that has about 2.3 million records. 我在数据库中有一个表,其中包含约230万条记录。

I need to export this data to a csv file through a java / web application. 我需要通过Java / Web应用程序将此数据导出到CSV文件。

I'm using JPA / Hibernate. 我正在使用JPA / Hibernate。 But I'm having trouble. 但是我有麻烦了。

HibernateEntityManager hem = this.getEntityManager().unwrap(HibernateEntityManager.class);
    Session session = hem.getSession();
    org.hibernate.Query qu = 
        session.createSQLQuery("select li.* from ligacoes li").
            setFetchSize(Integer.MIN_VALUE).setReadOnly(true);
    ScrollableResults r = qu.scroll(ScrollMode.FORWARD_ONLY);

    int count = 0;
    while (r.next()) {

But when the program reads about 200,000 records it throws an exception: 但是,当程序读取大约200,000条记录时,它将引发异常:

Exception in thread "ContainerBackgroundProcessor[StandardEngine[Catalina]]"  
java.lang.OutOfMemoryError: Java heap space

I've tried other means, but I'm still having difficulties. 我尝试了其他方法,但是仍然遇到困难。 I can't export the data directly from the database. 我无法直接从数据库导出数据。 The data must be exported through this application. 数据必须通过此应用程序导出。

Can anyone help? 有人可以帮忙吗?

I solved the question. 我解决了这个问题。

I split the query. 我拆分查询。 Instead of bringing a very large list, I bring a minor list several times. 我没有带来一个很大的清单,而是几次带来了一个次要清单。 Pagination. 分页。

        HibernateEntityManager hem = this.getEntityManager().unwrap(HibernateEntityManager.class);
        Session session = hem.getSession();

        int pageIn = 1;
        int pageFim = 20000;
        boolean fim = false;
        int count = 0;

        while (!fim) {
            ++count;
            org.hibernate.Query qu = session.createSQLQuery("select li.* from ligacoes li where li.operadora='81' "
                    + "and length(li.numero_destino) < 8 and li.valor_contrato <> '0'");
            qu.setFirstResult(pageIn - 1);
            qu.setMaxResults(pageFim);
            List<Ligacoes> chamadasVivo = new ArrayList<>(objectToLigacoes(qu.list()));

            count += pageFim;

            if (chamadasVivo.size() <= 0) {
                break;
            }

            for (Ligacoes li : chamadasVivo) {
                //append the file...

            }

            if (count % 100000 == 0) {
                session.flush();
                session.clear();
            }

            pageIn += pageFim;
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM