Monday, May 21, 2007

Using pojos as a data source for the jasper report


Using pojos as a data source for the jasper report

Here we'll know how to use the pojo as a data source instead of writing a SQL query inside the report.

  1. Create the report pojo.

  2. Create a pojo that represents your report data.

    if your report contains another subReport, your pojo will contains a list of the pojo that maps to the subReport data. so you will be in a need to add a function that returns the subReport list like the following one:


    public Object getSubReportArticlesList(){

    if (articlesList == null){

    articlesList = new ArrayList();

    }

    return new JRBeanCollectionDataSource( (ArrayList) articlesList , true);

    }



  3. Design you report.

  4. Now open your design tool and after finishing the static data, add data fields into your report but insure that this fields has the same name and type as your pojo attributes.

    if your report contains a subReport as we said before there will be a function inside the main pojo that will return the subReport data source, now we will handle it inside the design. create a field with the name of the method that returns the subReport data source like that subReportArticlesList it'll be handled by the jasper report framework as an ordinary attribute (name >> getName(), subReportArticlesList >> getSubReportArticlesList(), ....) and set that field as a data source for the subReport.


  5. Inside the report initialization method.

  6. you must specify the data source as a JRBeanCollectionDataSource.

1 comment:

Unknown said...

Hi
I am new in jasper. Could you please explain how we set a datasource for POJO in ireport