JasperReports: Using the Bean Collection Datasource

We’re using JasperReports to print a report about a single data object (specifically, a bean). Most of the samples available on the web refer to using a datasource that reads directly from a database or a CSV file. It took me a little bit of time to determine exactly how to do what I wanted to do.

Let’s assume that the bean that I am interested in reporting on is named Person. It’s got properties like firstName and lastName, as well as a field named homeAddress that is itself a bean of type Address.

First off, I designed the report layout using iReport. Whenever I’d need a field referenced on the bean, I’d define the field definition as it would look as if accessed from Person. Let’s say I added these fields to the report:

  • firstName
  • lastName
  • address.streetName
  • address.streetNumber
  • address.city
  • address.province
  • address.postalCode

Let’s call the report definition file PersonReport.jrxml. My Java code would look like this:

public void printPerson(Person person) throws JRException {

    List<Person> persons = new ArrayList<Person>();
    persons.add(person);

    JRBeanCollectionDataSource datasource = new JRBeanCollectionDataSource(persons);

    JasperReport jasperReport = JasperCompileManager.compileReport("c:/reports/PersonReport.jrxml");
    JasperPrint  jasperPrint = JasperFillManager.fillReport(jasperReport, new HashMap(), datasource);
    JasperExportManager.exportReportToPdfFile(jasperPrint, "c:/reports/person.pdf");
}

This approach has the advantage of easily scaling into printing multiple beans simply by increasing the size of the collection.

The actual code I ended up using is more complicated: I read the report definition off the resource path (and eventually I’ll want get a precompiled version), I’m actually delivering the PDF to a browser via a servlet, and I’m semi-intelligently handling the exceptions. I just wanted to document the (for me) tricky part of determining how to set up the datasource to use a bean and how to define the fields to reference the properties of the bean properly.

Note that iReport claims to have an import tool to allow you to read all the properties of a bean so you don’t have to type them in by hand. I’ve been unable to get that import utility to work.

It's only fair to share...
Share on FacebookGoogle+Tweet about this on TwitterShare on LinkedIn

Leave a Reply