Está en la página 1de 7

JSF + JPA + JasperReports (iReport) Part 2 | Ramki Java Blog

http://www.ramkitech.com/2012/06/jsf-jpa-jasperreports-ireport-part-2...

Discuss Java Concepts


Home All Posts Resume Contact Me About Me

Google

In this post is a continuation of Jasper Report Part 1. here we will discuss about some advanced jasper report concepts like passing complex object like List, Date object and how to create and use local variable in jasper report, Add the sub-report and background image to report. Check my latest post about Integrate Charts into Jasper Reports. here i am using JPA (Java Persistence API) for accessing the Database. so i create the two entity ShoppingCart and Item. here ShoppingCart entity contain list of Item entities. then i am going to pass these objects to Jasper Report. (Check the video in below)

179663

I'm on

ShoppingCart.java
view plain print ?

01. 02. 03. 04. 05. 06. 07. 08. 09. 10. 11. 12. 13. 14. 15.

@Entity public class ShoppingCart { @Id @GeneratedValue(strategy= GenerationType.AUTO) private long id; private String firstName; private String lastName; @Temporal(TemporalType.DATE) private Date dop; @OneToMany(cascade= CascadeType.ALL) private List<item> listOfItems; // getters and setters } </item>

ramkicse@gmail.com Mobile : +918605429395 Skype Id: ramkicse18

Item.java
view plain print ?

Rama krishnnan E P

01. 02. 03. 04. 05. 06. 07. 08. 09. 10. 11. 12.

@Entity public class Item { @Id @GeneratedValue(strategy= GenerationType.AUTO) private long id; private String itemName; private float price; private int noOfUnits; //getters and setters }

Create Report now i am going create report. we can use iReport standalone or iReport Netbeans Plugin to create the report. first we need to create some fields in report. these fields are matched with ShoppingCart Bean property names and Data types also.

195 have me in circles

View all

Rama krishnnan E P
29 vdeos | 573 suscriptores

Subscribe

Martin Murciego

1 de 7

06/03/2013 03:04 a.m.

JSF + JPA + JasperReports (iReport) Part 2 | Ramki Java Blog

http://www.ramkitech.com/2012/06/jsf-jpa-jasperreports-ireport-part-2...

Rama krishnnan E P View my complete profile

JSF + JPA + JasperReports (iReport) Part 1 Hi in this post we will see the overview of JasperReports and how to integrate into JSF application. JasperReports is the world's mo... and set the data types of these fields correctly. firstName ==> java.lang.String lastName ==> java.lang.String dop ==> java.util.Date listOfItems ==> java.util.List then drag these fields to detail pane of the report as per needs. then right click the Report and compile the report Virtual Host + Apache httpd server + Tomcat + mod_jk connector In my last post ( Virtual Host in Tomcat ) we discussed about how setup the virtual host in Tomcat. Its cost effective technique because on... JSF + JPA + JasperReports (iReport) Part 2 In this post is a continuation of Jasper Report Part 1 . here we will discuss about some advanced jasper report concepts like passing com... How to do SSH Tunneling (Port Forwarding) Screen-cast In this post we will see how ssh works?, what is SSH tunneling? what is important of ssh tunnels and how to setup the ssh tunnel. When SS... Running Multiple Tomcat Instances on Single Machine In this post we will see how to run multiple tomcat instances on single machine and under single user account. We first see the tomcat di...

then its creates the jasper file. and its compiled format of jasper report. check part 1 for more details of overview of jasper report. now create one JSF page with single Command Button (Submit Button)
view plain print ?

01. 02. 03. 04. 05. 06. 07. 08.

<h:head> <title>Facelet Title</title> </h:head> <h:body> <h:form> <h:commandbutton action="#{demoBean.pdf()}" value="Generate Jasper Report"> </h:commandbutton></h:form> </h:body>

and we create one managed bean for above JSF page DemoBean.java
view plain print ?

01. 02. 03. 04. 05. 06. 07. 08. 09. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20.

@ManagedBean @SessionScoped public class DemoBean { public void pdf() throws JRException, IOException { EntityManager em=PerisitenceManager.getEntityManager(); Query query= em.createQuery("select s from ShoppingCart s"); List<shoppingcart> listOfShoppingCart=(List<shoppingcart>)query.getResultList(); JRBeanCollectionDataSource beanCollectionDataSource = new JRBeanCollectionDataSource(listOfShoppingCar t); String reportPath = FacesContext.getCurrentInstance().getExternalContext().getRealPath("/reports /report.jasper"); JasperPrint jasperPrint = JasperFillManager.fillReport(reportPath, new HashMap(), beanCollectionDataSo urce); HttpServletResponse httpServletResponse = (HttpServletResponse) FacesContext.getCurrentInstance().getE xternalContext().getResponse(); httpServletResponse.addHeader("Content-disposition", "attachment; filename=report.pdf"); ServletOutputStream servletOutputStream = httpServletResponse.getOutputStream(); JasperExportManager.exportReportToPdfStream(jasperPrint, servletOutputStream); FacesContext.getCurrentInstance().responseComplete(); } }

CDI (5) JasperReports

Java (9) Java EE 6 (10)


(5) JSF (4)

JSF 2.0 (7)


load balancer (5) mod_jk (6) multiple_instances (6)

2 de 7

06/03/2013 03:04 a.m.

JSF + JPA + JasperReports (iReport) Part 2 | Ramki Java Blog

http://www.ramkitech.com/2012/06/jsf-jpa-jasperreports-ireport-part-2...

21.

</shoppingcart></shoppingcart>

screencast (22)
Tomcat (6) clustering (5) tomcat

Now when u run the project its generate the report in PDF file format. now we integrate the sub report. so drag the sub-report component from palettes. then add the Item beans property as a fields names and correct data types.

2013 (2) 2012 (13) December (1) November (1) October (2) and data types itemName ==> java.lang.String price ==> java.lang.Float noOfUnits ==> java.lang.Integer once sub report is ready then compile the subreports. while create the subreport we passed the Empty Data Source. so now we need to change to listOfItems as a data source, we can't pass directly because its not accept List. so we need to wrap into the JRBeanCollectionDataSource Object. so in main report select the sub report and change the properties Connection Type ==> Use a datasource Expression DataSource Expression ==> new net.sf.jasperreports.engine.data.JRBeanCollectionDataSource($F{listOfItems}) September (2) June (2) Deploy the Java Web Application to Jelastic Paas C... JSF + JPA + JasperReports (iReport) Part 2 April (2) March (1) February (1) January (1) 2011 (9) 2010 (7)

You Can Download this complete example from GitHub (or) google code . How to use

1. Change the properties in persistence.xml file, like db name, db hostname ,username and password. 2. Add necessary lib to class path like Hibernate libs, MySQL lib, Jasper Report lib. for simplicity in this zip contain war file under dist/ folder. so just extract and see all lib are located in WEB-INF/lib section. copy all files and add to to ur class path (Libraries ) 3. Create the jasperdb database in ur mysql server 4. First run the NewServlet , this servlet create necessary tables in ur database. and insert some sample rows to the table. 5. Finally run the index.xhtml file and generate the report.

3 de 7

06/03/2013 03:04 a.m.

JSF + JPA + JasperReports (iReport) Part 2 | Ramki Java Blog

http://www.ramkitech.com/2012/06/jsf-jpa-jasperreports-ireport-part-2...

I deployed same example in Jelastic Paas cloud, you can access through http://ramkicse.jelastic.servint.net/jasper/ URL click the button to generate the report. (Its expired) check How to deploy the Web application to Jelastic cloud

The last comments for

JSF JPA JasperReports (iReport) Part 2 ian Hi, yes i have getters and setters, the error from the firstName is now working but when i added the...
4 hours ago The last comments for

Check my latest post about Integrate Charts into Jasper Reports Screen Cast (Watch the video in HD)

JSF JPA JasperReports (iReport) Gabriel Instalacion rapida y sencilla sudo apt-get install libapache2-mod-jk
6 hours ago The last comments for

JSF JPA JasperReports (iReport) Part 2 Ramki 53p Hello Ian, Thanks, yes i ll help. So what is ur bean variable 'firstName'? and r u...
23 hours ago

ian Good Day! Great Tutorial! I watched your video on youtube. Anyway can you help me? I followed your tutorial...
23 hours ago The last comments for

Running Multiple Tomcat Instances on Single Machine Ramki 53p Thanks. mani i ll update the blog
1 day ago

Comments are Welcomed You might also like:

Comments by IntenseDebate

Posts
JSF + JPA + JasperReports (iReport) Integrate Charts in Jasper Reports +JSF 2.0 Understanding Java Server Faces 2.0 Part 1 Understanding Java Server Faces 2.0 Part 2 Integrate Chart Image into Jasper Report Part - 2

Comments

LinkWithin

Enter your email address:

Comments (24)
Sort by: Date Rating Last Activity emo 31 weeks ago good one! Thank you. It was very helpful to me.
Reply

Login

Delivered by FeedBurner
Report

little.hiti 28 weeks ago

Thanks a million boss, was stuck at the 'Connection Type ==> Use a datasource Expression DataSource Expression ==> new net.sf.jasperreports.engine.data.JRBeanCollectionDataSource($F{listOfItems})' point for quite a number of days. Now it works great.
Reply

with Google Friend Connect

Members (21) More Report

guru 25 weeks ago can i use font in fractions like(5.5) in jaspre reports.
Reply

2 replies active 25 weeks ago

Report
Already a member? Sign in

Ramki 53p 25 weeks ago yes

+1

4 de 7

06/03/2013 03:04 a.m.

JSF + JPA + JasperReports (iReport) Part 2 | Ramki Java Blog

http://www.ramkitech.com/2012/06/jsf-jpa-jasperreports-ireport-part-2...

Reply

Report

Ramki 53p 25 weeks ago There is Patter and Pattern Expression are available. Using that we can control fractions
Reply

+1

Report

jaswanth 23 weeks ago Nice article, thank you.


Reply

Report

Mahesh 20 weeks ago Very good article


Reply

Report

Aboudrar Brahim 17 weeks ago Thank you it's nice article In this example the type of listOfItems is List but when it's an object (for example Item) Can I use new net.sf.jasperreports.engine.data.JRBeanCollectionDataSource($F{Item})
Reply

1 reply active 17 weeks ago

Report

Aboudrar Brahim 17 weeks ago

Thank you it's nice article In this example the type of listOfItems is List but when it's an object (for example Item) Can I use new net.sf.jasperreports.engine.data.JRBeanCollectionDataSource($F{Item}) as the subreport's data sourse expression
Reply

Report

Ramki 53p 17 weeks ago

+2

but net.sf.jasperreports.engine.data.JRBeanCollectionDataSource is only accept Collection data types like List. so even u need to send single entity u need to wrap to List, then only u need to pass to it
Reply

Report

Aboudrar Brahim 16 weeks ago Finally it works fine Thank you very much A+
Reply

Report

Sriman 14 weeks ago hi....Ramki . thanks alot . your vedieo is more helpful to me. .....
Reply

Report

buddhika 14 weeks ago

Thank you very much. I am grateful to you for all your commitment helping us all. Sorry to bother you again by asking a question. Say the main report contain a Customer object instead of the firatName and surName. In that case how can we display the firstName and surName. Can we use a field like customer.firstName and customer.surName?
Reply

1 reply active 14 weeks ago

Report

Ramki 53p 14 weeks ago

+1

Yes, thats correct. u can use like F{customer.firstName} and $F{customer.surName} and make sure that customer filed datatype is Object.
Reply

Report

Gerard Mengerink 12 weeks ago

Thank you for this great demo. It is a step further then the first version I saw, which did return an exception. This one isn't complaining about anything (no exceptions) but is doesn't show a report either ! In fact ... nothing happens. The PDF method goes to its end without errors but I see no PDF output. Any clue to this ?
Reply

1 reply active 12 weeks ago

Report

Ramki 53p 12 weeks ago Hello Gerard Mengerink,

+1

5 de 7

06/03/2013 03:04 a.m.

JSF + JPA + JasperReports (iReport) Part 2 | Ramki Java Blog

http://www.ramkitech.com/2012/06/jsf-jpa-jasperreports-ireport-part-2...

first we need to call NewServlet then call the jasper page. check ur db u have enough records. and using google chrome developer tools and verify any response comes from server. If still problem persist the i can help through Teamviewer
Reply

Report

@muthaks 12 weeks ago Can you please make an example of taking an arbitrary Java object to PDF using Jasper
Reply

1 reply active 11 weeks ago

Report

Ramki 53p 11 weeks ago Hello muthaks, In this example Items Are also Objects. same approach we need to apply
Reply

+1

Report

Mantu Kumar 8 weeks ago great work....!!!!!


Reply

Report

Priya 2 weeks ago Thanks .. Great tutorial.I follow previous ireport chart. I have one problem.My code Map parameters = new HashMap(); List<CostSales> listOfCostSales = new ArrayList<CostSales>(); ....... listOfCostSales.add(new CostSales(actual_Cost, actual_Sale,cost,sale1,monthKey)); ..... parameters.put("listOfCostSales", listOfCostSales); ..... jasperPrint = JasperFillManager.fillReport(jasperReport,parameters,dataSource);

My jrxml file <parameter name="listOfCostSales" isForPrompting="false" class="java.util.List"/> ....... <lineChart> <chart hyperlinkTarget="Self" > <reportElement x="141" y="259" width="429" height="208" key="element-1"/> <box topBorder="None" topBorderColor="#000000" leftBorder="None" leftBorderColor="#000000" rightBorder="None" rightBorderColor="#000000" bottomBorder="None" bottomBorderColor="#000000"/> <chartLegend textColor="#000000" backgroundColor="#FFFFFF" > </chartLegend> </chart> <categoryDataset> <dataset > <datasetRun subDataset="ChartDataset"> <dataSourceExpression><![CDATA[new net.sf.jasperreports.engine.data.JRBeanCollectionDataSource($P{listOfCostSales})]]> </dataSourceExpression> </datasetRun> </dataset> </categoryDataset> <linePlot > <plot /> <categoryAxisLabelExpression><![CDATA[$P{month}]]></categoryAxisLabelExpression> <categoryAxisFormat> <axisFormat > </axisFormat> </categoryAxisFormat> <valueAxisFormat> <axisFormat > </axisFormat> </valueAxisFormat> </linePlot> </lineChart> where ChartDataset is my subreport have parameters Actual_cost ,Actual_sale,Sale,Cost and month which I want to use in my XY chart where month is in x axis and Others as values. How can i retrieve these values in my chart. when i try to run with $P{REPORT_PARAMETERS_MAP}.get( "Actual_Cost" ) I am getting empty key . I try to print in text box nothing is getting. Can you please help me to get values. I am new to ireport and last one week i am trying this. Thanks Priya
Reply

Report

Isaac 2 weeks ago Eres bien chingon, te admiro

6 de 7

06/03/2013 03:04 a.m.

JSF + JPA + JasperReports (iReport) Part 2 | Ramki Java Blog

http://www.ramkitech.com/2012/06/jsf-jpa-jasperreports-ireport-part-2...

Reply

Report

ian 23 hours ago

Good Day! Great Tutorial! I watched your video on youtube. Anyway can you help me? I followed your tutorial but I am having a little problem retrieving the records on my list. The error goes like this: net.sf.jasperreports.engine.JRException: Error retrieving field value from bean : firstName I hope you can help me. Thanks man!
Reply

Report

Ramki 53p 23 hours ago Hello Ian, Thanks, yes i ll help. So what is ur bean variable 'firstName'? and r u have getter / setters?
Reply

+1

1 reply active 4 hours ago

Report

ian 4 hours ago

Hi, yes i have getters and setters, the error from the firstName is now working but when i added the listOfItems it gives me the same error. Now the error looks like this: net.sf.jasperreports.engine.JRException: Error retrieving field value from bean : listOfItems thanks for your help man!
Reply

Report

Post a new comment


Enter text right here!

Comment as a Guest, or login: Name


Displayed next to your comments.

Email
Not displayed publicly.

Website (optional)
If you have a website, link to it here.

Subscribe to

Submit Comment

Posted by Rama krishnnan E P at Thursday, June 21, 2012


+3 Recommend this on Google

Tags : JasperReports, Java SE, javaEE, JSF 2.0, screencast

Newer Post

Home

Older Post

Template images by Jason Morrow. Powered by Blogger.

7 de 7

06/03/2013 03:04 a.m.

También podría gustarte