Use Java beans as Jasper Reports data source with JRBeanCollectionDataSource

As you can see in iReport, Jasper Reports provides support for several data source types.

 Jasper Reports JRBeanCollectionDataSource

JRBeanCollectionDataSource is a convenient way to use Java beans collections in a Jasper Reports. For example suppose you have a Person bean and a class that returns a collection of Java beans:

// File Person.java
//
public class Person {
private String name;
publig String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
}

 

// File PeopleProvider.java
//
public class PeopleProvider {
public Collection<Person> findPeopleAll() {
// ..Code that returns a collection of Peron's objects..
}
}

 

Create a JasperReports report with JRBeanCollectionDataSource

To use the bean create a new Jasper Reports report and, in the FIelds list of Report Inspector, add all your bean fields (name in the case of Person bean). Simply click on Fields -> Add Field.

Jasper Reports java bean collection

Make sure all the fields you define in Fields list exists in the Java class (Person), have the getFieldname() getter method syntax and you have a compatible data type set in Properties palette.

The Fields in Fields list can then be dragged in the report and used to print data.

Execute JasperReport report from Java

Now it's time to write the Java code that executes your Jasper Reports report. You can execute a report saved in the compiled .jasper format or in the source .jrxml format. Here is an example on how to run a .jasper (compiled) report file by passing a java Collection as data source:

public class ReportDemo {
public void execute(Collection<Person> data) {
HashMap<String,String> parameters = new HashMap<String,String>();
InputStream reportStream = new FileInputStream("yourReportFile.jasper");
// Bing the datasource with the collection
JRDataSource datasource = new JRBeanCollectionDataSource(data, true);
// Print the jasper report
JasperPrint print = JasperFillManager.fillReport(reportStream, parameters, data);
JasperPrintManager.printReport(print, true);
}
}

Hew is an example on how to print a Jasper Reports saved in the .jrxml format:

public class ReportDemo {
public void execute(Collection<Person> data) {
HashMap<String,String> parameters = new HashMap<String,String>();
InputStream reportStream = new FileInputStream("yourReportFile.jrxml");
// Bing the datasource with the collection
JRDataSource datasource = new JRBeanCollectionDataSource(data, true);
// Compile and print the jasper report
JasperReport report = JasperCompileManager.compileReport(reportStream);
JasperPrint print = JasperFillManager.fillReport(report, parameters, datasource);
JasperPrintManager.printReport(print, true);
}

The Java application requires the Jasper Reports jar libraries (jasperreports.jar, itext.jar for PDF, etc) copied in the path to run as well as the report file.