You are here: Platform Specific Issues > Reporting > db4o with Jasper Reports Example

db4o with Jasper Reports Example

This example illustrates how you can use Jasper Reports together with db4o to create a report. Take a look at the official Jasper Reports website for the documentation and tools around Jasper Reports.

Designing the Report

The report layout is written as an XML file or alternatively you can use an editor like the iReport-editor.

For adding data you can declare fields, which then are used for each row of the report. Just use the names of your properties which you want to report. For navigating along the data separate the properties with dots:

<field name="sirname" class="java.lang.String"/>
<field name="firstname" class="java.lang.String"/>
<field name="address.city" class="java.lang.String"/>
report.jrxml: declare fields

After that you can access these fields in the report:

<textField>
	<reportElement x="0" y="0" width="100" height="21"/>
	<textFieldExpression class="java.lang.String"><![CDATA[$F{sirname}]]></textFieldExpression>
</textField>
<textField>
	<reportElement x="100" y="0" width="100" height="21"/>
	<textFieldExpression class="java.lang.String"><![CDATA[$F{firstname}]]></textFieldExpression>
</textField>
<textField>
	<reportElement x="200" y="0" width="100" height="21"/>
	<textFieldExpression class="java.lang.String"><![CDATA[$F{address.city}]]></textFieldExpression>
</textField>
report.jrxml: Placing the fields on the report

Filling the Report

After that you can fill the report with data from the database. For simpler reports we can use the JRBeanCollectionDataSource, which reads the values from regular Java bean objects. For more complex reports you might need to use another data source which you can fill manually like the JRMapCollectionDataSource. For all the available datasources read the Jasper Reports documentation.

final ObjectSet<Person> queryResult = container.query(new Predicate<Person>() {
    @Override
    public boolean match(Person p) {
        return p.getSirname().contains("a");
    }
});
final JRBeanCollectionDataSource dataSource = new JRBeanCollectionDataSource(queryResult);
final JasperPrint jasperPrint = JasperFillManager.fillReport(report, new HashMap(), dataSource);
JasperExportManager.exportReportToPdfFile(jasperPrint, "the-report.pdf");
JasperReportsExample.java: Run a query an export the result as report