Jasper report hibernate data source


/ Published in: Java
Save to your folder(s)

The data source which can be used in combination with jasper reports.


Copy this code and paste it in your HTML
  1. import net.sf.jasperreports.engine.JRDataSource;
  2. import net.sf.jasperreports.engine.JRException;
  3. import net.sf.jasperreports.engine.JRField;
  4. import java.util.*;
  5.  
  6. public class HibernateQueryResultDataSource implements JRDataSource {
  7.  
  8. private final Iterator<Map<String, Object>> iterator;
  9.  
  10. private Map<String, Object> currentValue;
  11.  
  12. /**
  13. this is only for clarity
  14. */
  15. private final String name;
  16.  
  17. public HibernateQueryResultDataSource(List<Map<String, Object>> list, String name) {
  18. this.iterator = list.iterator();
  19. this.name=name;
  20. }
  21.  
  22. public Object getFieldValue(JRField field) throws JRException {
  23. return currentValue.get(field.getName());
  24. }
  25.  
  26. public boolean next() throws JRException {
  27. currentValue = iterator.hasNext() ? iterator.next() : null;
  28. return (currentValue != null);
  29. }
  30.  
  31. public Iterator<Map<String, Object>> getIterator() {
  32. return iterator;
  33. }
  34.  
  35. }
  36.  
  37.  
  38. // A usage example
  39.  
  40. private JRPdfExporter jRPdfExporter;
  41.  
  42. private boolean compileAndCreatePDF(final String pdfFileName, final JRDataSource ds){
  43. try {
  44. jRPdfExporter.setParameter(JRPdfExporterParameter.CHARACTER_ENCODING, "UTF-8");
  45. jRPdfExporter.setParameter(JRPdfExporterParameter.FONT_MAP, fontMap);
  46. final JasperPrint jasperPrint = JasperFillManager.fillReport(GeneratedPath + compiler.getRelevantEntryReportName(), new HashMap(0), ds);
  47. jRPdfExporter.setParameter(JRPdfExporterParameter.JASPER_PRINT, jasperPrint);
  48. jRPdfExporter.setParameter(JRPdfExporterParameter.OUTPUT_FILE_NAME, System.getProperty("java.io.tmpdir") + "/" + pdfFileName);
  49. jRPdfExporter.exportReport();
  50. return true;
  51. } catch (Exception e) {
  52. log.error(e);
  53. return false;
  54. }
  55. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.