Hibernate - 将结果集加载到内存

时间:2017-07-24 19:57:32

标签: hibernate jpa spring-boot apache-poi

我有简单的报表机制,它从数据库加载对象列表,并将它们写在excel文件中(Apache POI)

public List<Exhibitor> exhibitorReport(String fromDate, String toDate, String 
   exhibitorName) {

    DateTime dateTimeFrom = null;
    DateTime dateTimeTo = null;

    CriteriaBuilder builder = em.getCriteriaBuilder();

    CriteriaQuery<Exhibitor> cq = builder.createQuery(Exhibitor.class);

    Root<Exhibitor> from = cq.from(Exhibitor.class);

    List<Predicate> predicates = new ArrayList<Predicate>();

    if (!"".equals(exhibitorName)) {
        predicates.add(builder.equal(from.get("name"), exhibitorName));
    }

    if (!"".equals(fromDate)) {
        if (!StringUtils.isBlank(fromDate)) {
            DateTimeFormatter fmt = DateTimeFormat.forPattern("d-M-y");
            dateTimeFrom = DateTime.parse(fromDate, fmt);
            predicates.add(builder.greaterThanOrEqualTo(from.get("created"), dateTimeFrom));
        }
    }
    if (!"".equals(toDate)) {
        if (!StringUtils.isBlank(toDate)) {
            DateTimeFormatter fmt = DateTimeFormat.forPattern("d-M-y");
            dateTimeTo = DateTime.parse(toDate, fmt);
            predicates.add(builder.lessThan(from.get("created"), dateTimeTo.plusDays(1)));
        }
    }

    cq.select(from).where(predicates.toArray(new Predicate[] {}));
    return em.createQuery(cq).getResultList();
}

这里的一切都很完美。我有参展商名单。 使用下面的代码,我只是将一些属性从List写入XLSX。

  @Override
  protected void buildExcelDocument(Map<String, Object> model, Workbook workbook, 
   HttpServletRequest request, HttpServletResponse response) throws Exception {

    response.setHeader("Content-Disposition", "attachment; 
   filename=\"ExhibitorReport.xlsx");
    List<Exhibitor> exhibitors = (List<Exhibitor>) model.get("exhibitors");

    Sheet sheet = workbook.createSheet("ExhibitorReport");
    Row header = sheet.createRow(0);
    header.createCell(0).setCellValue("Country");
    header.createCell(1).setCellValue("City");
    header.createCell(2).setCellValue("Distributor");
    header.createCell(3).setCellValue("Address");
    header.createCell(4).setCellValue("ExhibitorName");
    header.createCell(5).setCellValue("CatalogueId");

    int counter = 1;

    for (Exhibitor exhibitor : exhibitors) {
        Row row = sheet.createRow(counter);
        row.createCell(0).setCellValue(exhibitor.getDistributor().getCountry());
        row.createCell(1).setCellValue(exhibitor.getDistributor().getCity());
        row.createCell(2).setCellValue(exhibitor.getDistributor().getName());
        row.createCell(3).setCellValue(exhibitor.getDistributor().getAddress());
        row.createCell(4).setCellValue(exhibitor.getName());
        row.createCell(5).setCellValue(exhibitor.getCatalogueNumber());

        counter++;
    }

}

再一点没什么特别的...问题是这个调用 SELECT 查询每一行(对于每个Distributor对象),这可以毫无问题地对DB进行10K查询。如何只为整个列表编写只有一个SELECT的对象。

0 个答案:

没有答案