Subreport in Jasper


Example: 1

IReport / JasperReports – Adding a subreport in the main report and using main parameters in subreport



12 Votes

Finally i spared myself some time to upgrade my Jasper Server to version 3.7.5 on Glassfish V 3.0.1, and as a consequence, i got to (finally) set up the 3.7.5 version of IReport on my Windows 7 machine.Back to the Jasper World…i’ve been missing it!
The last thing i covered on IReport and JasperReports, (other than configuring Jasper Server for Glassfish V3) was how one can use main dataset parameters in subdatasets. One of you blog readers (Brad) asked the question:
“But what if I don’t want to use my subdataset for a chart/graph? I just want to use the main report’s parameter in the subdataset query.”
This is what i am going to talk about now

Step 1 – Add a subreport in the Jasper Repository

In order to add a subreport in your main report, you have to design the subreport first, and it has to exist, as a independent entity in the Jasper Server Report Repository. I used the following structure:
  • Main Reports(Folder)
    • Response Times Report (Report)
  • Subreports (Folder)
    • statistics (Report)

Step 2 – Add a subreport to the main Jasper Report

Open the main report. Select the “Subreport” element from the Report Elements, and draw it on your main report
Subreport Ireport / Jasper Report
Subreport Ireport / Jasper Report
You now have to link the subreport element that you just added to the main report, to yoursubreport file (the one you created in step 1) In order to do that, select the subreport element in the main report, and modify its parameters as follows:
  • Subreport Expression: “repo:statistics”
  • Expression Class: java.lang.String
  • Connection Type: Use a connection expression
  • Connection Expression: $P{REPORT_CONNECTION}
Mapping subreport in Jasper Report

Step 3 – Adding and mapping the parameters between the main report and the subreport

The “Response Times Report” contains our subreport called “statistics”. The statistics report is supposed to calculate and show in a table format the following values:
  • the Request Name
  • total transactions
  • average response time
  • standard deviation
  • 50 to 90 response time percentile
In order to calculate this values, we need to know some information like:
  • the build id (software package version)
  • scenarioname (the name of the test scenario)
  • architecture name ( the type of test: baseline, performance, load)
  • runid (the id of the testrun)
We will get these parameters by passing them from the main report to the subreport. The rule is, for every parameter we want to pass to a subreporta similar parameter (with another name) has to exist in the subreport, so that we can make the mapping. We discussed about four parameters that we need from the main report:
Parameters in Response Times Report (Main Report) : build_number, test_scenario_name, architecture_name,run_id
Parameters that we NEED to define in the Statistics Report (Subreport): buildnumber, scenarioname, architecturename,runid
This is how the subreport looks like (including the defined subreport parameters; note: the currently open report is the “statistics” subreport, and the values in the left column are the“subreport parameters”)
IReport - Subreport parameters
After we added the parameters in the subreport, all we need to do is to map the main parameters to the “subparameters” As you see in the image above (step 2), the Parameters property shows “4 properties defined”. Let’s open the Properties view of the subreport once more, and do the mapping ( note: the currently open report is the main report, and the values in the left column are the main parameters):
Passing parameters to subreport in Jasper Report using IReport
Passing parameters to subreport in Jasper Report using IReport
As you can see, the “name” column accounts for the main report parameters, whereas the“expression” column accounts for the subreport parameters. We are now ready to use the“passed parameters” in our subreport.

Step 4 – Using the passed / mapped main report parameters as subreport parameters in a query

This is the simplest part: you just need to use the subreport parameters in the “FROM” condition of your query. Example below:
select …..from….where info.build=$P{build_number} and td.scenario_id=$P{test_scenario_name} and td.architecture_id=$P{architecture_name}

ADDITION – IMPORTANT
After looking over some of the questions that some of you asked, it ocurred to me that the example above, where the subreport resides in another folder, requires an additional setting.
If for example your main report resides in the “main reports” folder, and your subreport in the “subreports” folder (where “main reports” and “subreports” reside at the same level in the folder tree, under “reports” root folder) you will have to add the subreport as a resource reference, like in the picture below:
IReport subreport reference
IReport subreport reference

Example:2
This is a simple way to create a subreport in jasper reports. Most of the beginners will get the use from it. 
My project is going to be a single page with details of a CV. It will look like below

Before all these, the structure of data resources in parameters of the jasper report is going to be as follow


 Im not using data models to pass these data, so making model classes to this will have no use. The output can be get from following java code.

I used a main method just show how its done.

public static void main(String[] args) {
try {
Object[] cols={"Subject", "Result"}; 
DefaultTableModel dtm=new DefaultTableModel(cols, 0);
dtm.addRow(new Object[]{"Mathematics","B"});
dtm.addRow(new Object[]{"Physics","A"});
dtm.addRow(new Object[]{"Chemistry","B"});

JRTableModelDataSource jrtAL = new JRTableModelDataSource(dtm); //Add DefaultTableModel to the //JRTableModel

Map SUB_DATA1=new HashMap(); //This will hold A/L Data
SUB_DATA1.put("jrtAL", jrtAL);
dtm=new DefaultTableModel(cols, 0);
dtm.addRow(new Object[]{"Mathematics","B"});
dtm.addRow(new Object[]{"Physics","A"});
dtm.addRow(new Object[]{"Chemistry","B"});

JRTableModelDataSource jrtOL = new JRTableModelDataSource(dtm);
Map SUB_DATA2=new HashMap();
SUB_DATA2.put("jrtOL", jrtOL);
List data=new ArrayList();
Map dataMap=new HashMap();
dataMap.put("topic", "Web Developing\nCertificate");
dataMap.put("desc", "Diploma in Web Developing\n(Global Solution Technologies) ");
data.add(dataMap);
dataMap=new HashMap();
dataMap.put("topic", "Computer Certificates");
dataMap.put("desc", "Diploma in computer Technology\n(Microtech Computer Systems) ");
data.add(dataMap);

JRMapCollectionDataSource subDS=new JRMapCollectionDataSource(data);

Map SUB_DATA3=new HashMap();
SUB_DATA3.put("subDS", subDS);

String repSource = "./src/report/CVReport.jrxml";
Map<String, Object> param = new HashMap<String, Object>();
param.put("SUB_DATA1", SUB_DATA1);
param.put("SUB_DATA2", SUB_DATA2);
param.put("SUB_DATA3", SUB_DATA3);
///////////////////////////////////////////////////////
Map simpleMasterMap = new HashMap();
String name="San Buddy CV";
String address="No 1, Somewhere,\nSomewhere ";
String resTel="091-1234567";
String phone="071-6204835";
String email="somebody@gmail.com";
String profile="To excel in the field of web developing relating to business and academic industry, "
+ "with highly proven leadership skills involving developing projects, managing projects and ability to"
+ " work with own initiative or and as part of team, is now seeking a profession in the field of web "
+ "application development and willing to dedicate myself strictly to adhere the employment ethics and to"
+ " thrive my best for the respective company’s success. ";

simpleMasterMap.put("name", name);
simpleMasterMap.put("address", address);
simpleMasterMap.put("resTel", resTel);
simpleMasterMap.put("phone", phone);
simpleMasterMap.put("email", email);
simpleMasterMap.put("profile", profile);

List simpleMasterList = new ArrayList();
simpleMasterList.add(simpleMasterMap);
JRMapCollectionDataSource simpleDS = new JRMapCollectionDataSource(simpleMasterList);

JasperReport jr = JasperCompileManager.compileReport(repSource);
JasperPrint jp = JasperFillManager.fillReport(jr, param, simpleDS);
JasperViewer.viewReport(jp);
} catch (JRException ex) {
JOptionPane.showMessageDialog(null, "Jasper Error: \n"+ex.getMessage());
}



With this jasper report produced a report like this.. 


Here 

  1. Advanced Level
  2. Ordinary Level
  3. Extra Educational Qualifications
were made with subreports. 
This is how it looked like in IReport 4.5
CVReport.jrxml


CVSubOL.jrxml

CVSub3.jrxml
CVExtra.jrxml

In the CVReport, all details have fields that were passed in main method using "simpleDS" JRMapCollectionDataSource.
You must create three parameters with SUB_DATA1, SUB_DATA2 and SUB_DATA3 each having parameter class of java.util.HashMap pass dataresources to subreports. You can edit this in Properties tab after selecting parameter created in the report inspector or can write following code in jrxml 

<parameter name="SUB_DATA1" class="java.util.HashMap"/>
<parameter name="SUB_DATA2" class="java.util.HashMap"/>
<parameter name="SUB_DATA3" class="java.util.HashMap"/>

I have used three detail bands to insert subreports. You can add subreports by drag and dropping a sub report to the editing report or by editing XML. Subreport is also a normal jasper report and only difference it makes is, we use it as a sub report to a main report. 
Here is the code of the subreport code in the main report.

<band height="85" splitType="Stretch">
<subreport>
<reportElement x="0" y="22" width="555" height="47"/>
<subreportParameter name="id1">
<subreportParameterExpression><![CDATA[$P{SUB_DATA1}.get("jrtAL")]]></subreportParameterExpression>
</subreportParameter>
<dataSourceExpression><![CDATA[$P{SUB_DATA1}.get("jrtAL")]]></dataSourceExpression>
<subreportExpression><![CDATA[$P{SUBREPORT_DIR} + "CVSub3.jasper"]]></subreportExpression>
</subreport>
<staticText>
<reportElement x="19" y="2" width="163" height="20"/>
<textElement>
<font fontName="Calibri" size="15" isBold="true"/>
</textElement>
<text><![CDATA[Advanced Level (2011)]]></text>
</staticText>
</band>

I have used SUB_DATA1 jrtAL dataresource for first CVSub3 subreport. As SUB_DATA1 is a HashMap class parameter, you can use get(String) method to get a object.

In CVSub3, I have used two fields "Subject" and "Result" to print the table in detail band. Simply it will do the work of sub reporting. 

*You must change the language of the main report to groovy and subreport language to java. Otherwise it will bring out a compile error. 


Likewise you can create other two subreports and little change that I have done in SUB_DATA3 wont affect it. There, I have used a JRMapCollectionDataSource "subDS" and you can get details using two fields "desc" and "topic". 

Other two subreport declarations are below
<band height="83">
<subreport>
<reportElement x="0" y="20" width="555" height="48"/>
<subreportParameter name="id2">
<subreportParameterExpression><![CDATA[$P{SUB_DATA2}.get("jrtOL")]]></subreportParameterExpression>
</subreportParameter>
<dataSourceExpression><![CDATA[$P{SUB_DATA2}.get("jrtOL")]]></dataSourceExpression>
<subreportExpression><![CDATA[$P{SUBREPORT_DIR} + "CVSubOL.jasper"]]></subreportExpression>
</subreport>
<staticText>
<reportElement x="19" y="0" width="163" height="20"/>
<textElement>
<font fontName="Calibri" size="15" isBold="true"/>
</textElement>
<text><![CDATA[Ordinary Level (2008)]]></text>
</staticText>
</band>
////////////////////////////////////////////////////
<band height="86">
<subreport>
<reportElement x="0" y="26" width="555" height="60"/>
<subreportParameter name="id2">
<subreportParameterExpression><![CDATA[$P{SUB_DATA3}.get("subDS")]]></subreportParameterExpression>
</subreportParameter>
<dataSourceExpression><![CDATA[$P{SUB_DATA3}.get("subDS")]]></dataSourceExpression>
<subreportExpression><![CDATA[$P{SUBREPORT_DIR} + "CVExtra.jasper"]]></subreportExpression>
</subreport>
<staticText>
<reportElement x="19" y="0" width="276" height="26"/>
<textElement>
<font fontName="Calibri" size="15" isBold="true"/>
</textElement>
<text><![CDATA[Extra Educational Qualifications]]></text>
</staticText>
</band>

Post a Comment

Thank You

Previous Post Next Post