Welcome!

Java Authors: Pat Romanski, Carmen Gonzalez, Victoria Livschitz, Liz McMillan, Elizabeth White

Related Topics: Java

Java: Article

Reporting Made Easy with JasperReports and Hibernate

JasperReports and Hibernate in Web applications

JasperReports is a valuable and viable reporting solution for Java Web applications. It simplifies report generation through the use of XML report templates that are then compiled using the JasperReports engine for use in reporting modules. These compiled report templates can be filled by data received from a variety of sources including relational databases. JasperReports can be integrated into Web applications and create reports in several file formats including PDF and XLS.

Reporting in Java Applications
Often reporting modules increase in complexity and size during the course of application development. Clients tend to demand more information from report modules when they become aware of the benefits reports offer. The reporting module developed as something of an afterthought in such environments suddenly becomes a much more integral part of the application. Reporting modules often seem to be tacked on to developed applications, rather than being considered and implemented during initial application development.

Recently while working on some applications that made extensive use of report extraction to XLS files using the Apache POI library, it became apparent that these report modules tied up lots of valuable development resources for extended periods of time. When the client requested PDF extraction, initial iText API research led me to discover JasperReports. JasperReports was to change our team approach to report development dramatically.

Prior to implementing JasperReports each report creation required the development of a custom report class using the Apache POI library. This approach expended valuable development time creating aspects of the report such as cell specific formats, styles, and population methods. JasperReports offered our team the ability to get back this valuable development time, while producing the same report because of its embedded use of the Apache POI library.

One of the benefits offered by the introduction of JasperReports is that a single report template implementation can produce reports in a number of formats. This means that templates created for XLS format extraction can also be used to produce PDF files and even CSV, HTML or XML.

How Can JasperReports Help Developers?
JasperReports gives developers the ability to create reports quickly and easily that can be extracted to numerous formats. Developers can also use the JasperReports engine to compile report templates at design or runtime - allowing dynamic report formats. Developers can also inject data into these reports from a number of data sources. Developer time no longer has to be spent creating custom report classes using the Apache POI or iText libraries for formatting and stylizing reports, allowing the code writers to focus on the data retrieval aspect of the report. As a result developers gain valuable flexibility and time savings using JasperReports in application development.

The XML report templates used by JasperReports provide the layout and presentation information required to format the resulting report as well as field, variable, and parameter references. Non-development staff can create these templates using a third-party GUI such as iReport with minimal developer collaboration, so developers don't have to involve themselves in the layout and presentation aspect of report generation.

JasperReports enables developers to concentrate their efforts on the parts of the reporting module where they are required, while relieving them of having to write custom report generation code. A developer's role in the report module can be reduced to template compilation, data source implementation, and actual report creation.

Creating and Compiling an XML Report Template
JasperReports requires a report design defining the layout, presentation, and data fields. This design can be built using the net.sf.jasperreports.engine.design.JasperDesign object, so developers can create report designs dynamically, or by creating a net.sf.jasperreports.engine.design.JasperDesign instance from an XML report template. Unless an application specifically requires a dynamic layout a compiled XML report template is the recommended method. This XML template is usually saved with a .jrxml file extension and compiled using the net.sf.jasperreports.engine.JasperCompileManager.

The JasperReports XML template includes elements for <title>, <pageHeader>, <columnHeader>, <pageFooter>, <columnFooter>, and the main data <detail> element. Each of these elements has a variety of sub-elements as can be seen in sampleReport.jrxml (see Listing 1).

You can download the code samples used in this article at jdj.sys-con.com. As can be seen in sampleReport.jrxml some elements such as <band> and <reportElement> contain layout information, while others such as <textElement> and <font> contain presentation information. The XML templates also contain <parameter>, <field>, and <variable> elements used to include data in the report.

The <parameter> elements allow non-data source information to be passed into a report, such as a dynamic title; <field> elements are the only way to map report fields to the data source fields, while variables are values generated at runtime for use in the report. The complete Document Type Definition (DTD) for the JasperReports XML report template can be found in the JasperReports Ultimate Guide.

Compilation of the XML template can be done either at runtime or build time as part of an Ant build using the JasperReports Ant task.

Compiling the report at runtime entails loading the report into a JasperDesign object and using the created instance as the parameter to the JasperCompileManager.compileReport(JasperDesign design) method, which returns a JasperReport instance. Alternatively the XML template can be passed into the JasperCompileManager.compileToFileReport(String sourceFileName, which creates a compiled report file (.jasper) available throughout the application.

Compiling the report at build time using the JasperReports Ant task requires the addition of the task definition to the build.xml file and a target making use of this task as seen in Listing 2, which is an extract from the source code build.xml. Using the Ant task results in the creation of a compiled (.jasper) file in the destdir task and offers the opportunity to save the Java source file by passing the keepjava attribute of the target a true value. A more thorough example of how to use the Ant task is included in the sample applications provided in the JasperReports download bundle.

Using Data Sources to Fill JasperReports
Most reports use a database as the data source, but JasperReports can use any available data source. These data sources are passed to a net.sf.jasperreports.engine.JasperFillManager fillReportXXX() method. Two types of data source are provided for by these methods - net.sf.jasperreports.engine.JRDataSource and java.sql.Connection. The source code for this article contains examples of both a static data source that extends the JRDataSource and a JDBC connection data source implementation.

The StaticDataSource class implementation provided implements the net.sf.jasperreports.engine.JRDataSource interface enabling it to fill the report data by calling the JasperFillManager.fillReport(JaperReport report, Map parameters, JRDataSource dataSource) method. The two required methods getFieldValue(JRField jrField) and next() of the JRDataSource interface present in StaticDataSource handle the data passing from the data source into the JasperReport. The data source used by StaticDataSource is a static simple two-dimensional array of bowlers containing their names and scores over three games (see Listing 3). When the fillReport() method containing this data source is processed and a detail section is encountered in the report a call will be made to the next() method. The implementation of this method in StaticDataSource (see Listing 4) returns true if there's another element in the data array, or false if there is no more data. If this method returns true then field elements encountered in the detail section will result in a call to the getFieldValue(JRField jrField) method in StaticDataSource. The implementation of this method in StaticDataSource (see Listing 5) returns the value of the mapped data field name for the current index of the data array. When the end of the detail section is encountered, the next() method is called again and the process repeats until the next() method returns false.

The JDBCDataSourceExample (see Listing 6) implements a fillReport() method that accepts a java.sql.Connection parameter. Through the addition of a <queryString> element into the XML report template (jdbcSampleReport.jrxml) this fillReport() method enables data to be extracted from a relational database. The <queryString> element returns the data fields for use in the report data mapping. In this case the query simply returns all records in the sample_data table. A java.sql.ResultSet can be used instead of implementing the <queryString> element in the report template, allowing dynamic query implementation.

Using Hibernate with JasperReports
Hibernate is one of the most popular ORM tools in use at the moment. Using Hibernate as a data source for JasperReports can be very simple when a collection of objects is returned from a Hibernate query, but when a tuple of objects is returned then a custom JRDataSource implementation is required.

When a Hibernate query returns a collection of objects, a net.sf.jasperreports.engine.data.JRBeanCollection-DataSource can be used to map the Hibernate POJO instance fields to the report fields. All that's required for this simple solution is to use the JRBeanCollectionDataSource(java.util.Collection beanCollection) constructor, passing it the Hibernate Query result set as implemented in SimpleHibernateExample (see Listing 7). In this example the simple Hibernate query used (session.createQuery("from SampleData").list()) is equivalent to that found in the JDBCDataSourceExample. JRBeanCollectionDataSource implements JRDataSource like StaticDataSource but its getFieldValue(JRField jrField) method implementation maps the report template field names to the query result bean properties.

When a Hibernate query returns a tuple of objects it's necessary to write a custom implementation of the JRDataSource similar to HibernateDataSource (see Listing 8). The implementation of the required next() method in this class returns true if there is another list item in the Hibernate query result set, while putting the current list item in a currentValue holder for use in the getFieldValue(JRField jrField) method. The getFieldValue() method implementation gets the field index in the currentValue object via a call to the getFieldIndex(String field) method. This method iterates through the mapped field names passed to the HibernateDataSource constructor until it finds the field name it was passed and then returns the index of this field in the currentValue information. The getFieldValue() method then returns the value at this index in the currentValue result object.

More Stories By Peter Sellars

Peter Sellars is the lead devloper at Netbyte Internet Ltd
(www.netbyte.com) in Auckland, New Zealand. His main interests are project
automation and application architecture. He aims to simplify developer jobs by
implementing tools that enable them to utilise their time better. He
enjoys playing soccer and tenpin bowling.

Comments (8) View Comments

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.


Most Recent Comments
Abhilash.T.G 10/01/07 10:40:22 AM EDT

Very informative at the same time simple presentation.

Rob K 02/27/06 09:00:51 PM EST

ant build runs (compiles) the reports, looks like directory tree good from build, but doesn't create a .war file?

anyone offer assistance?

also, anyone figure out how to run this under ireport 1.1 and hibernate v3?

thanks
rob

Rob K 02/27/06 01:26:22 PM EST

seems to be very 'glossed' over in terms of what versions of the products are used or setup...

1. like why is this hibernate v2 and not v3?
2. what versions of jasper & ireport are being used?
3. how is a datasource configured for hibernate via ireport?

too much missing that's beyond the code (but would love to hear the 'rest of the story')

rob

Yvonne Gevers 02/27/06 05:23:32 AM EST

Hi,

If I want to put the result of the example into a jsp page, but I don't know how to do this. Can you give me an example of this?

Thank you.

Yvonne

James Nixon 02/20/06 03:39:19 PM EST

http://res.sys-con.com/story/jan06/171467/sellars1101.zip

I found the source by following the "See Listing 1" link on the first page.

Jose Gulisano 02/10/06 12:57:45 PM EST

Any news on source code? I t would really help given the well written article.

Thanks!!

Ashutosh Mittal 02/09/06 12:06:51 PM EST

Where to download the source code for this excellent article?

news desk 01/25/06 09:52:50 PM EST

JasperReports is a valuable and viable reporting solution for Java Web applications. It simplifies report generation through the use of XML report templates that are then compiled using the JasperReports engine for use in reporting modules. These compiled report templates can be filled by data received from a variety of sources including relational databases. JasperReports can be integrated into Web applications and create reports in several file formats including PDF and XLS.

@ThingsExpo Stories
Cultural, regulatory, environmental, political and economic (CREPE) conditions over the past decade are creating cross-industry solution spaces that require processes and technologies from both the Internet of Things (IoT), and Data Management and Analytics (DMA). These solution spaces are evolving into Sensor Analytics Ecosystems (SAE) that represent significant new opportunities for organizations of all types. Public Utilities throughout the world, providing electricity, natural gas and water, are pursuing SmartGrid initiatives that represent one of the more mature examples of SAE. We have s...
The security devil is always in the details of the attack: the ones you've endured, the ones you prepare yourself to fend off, and the ones that, you fear, will catch you completely unaware and defenseless. The Internet of Things (IoT) is nothing if not an endless proliferation of details. It's the vision of a world in which continuous Internet connectivity and addressability is embedded into a growing range of human artifacts, into the natural world, and even into our smartphones, appliances, and physical persons. In the IoT vision, every new "thing" - sensor, actuator, data source, data con...
How do APIs and IoT relate? The answer is not as simple as merely adding an API on top of a dumb device, but rather about understanding the architectural patterns for implementing an IoT fabric. There are typically two or three trends: Exposing the device to a management framework Exposing that management framework to a business centric logic Exposing that business layer and data to end users. This last trend is the IoT stack, which involves a new shift in the separation of what stuff happens, where data lives and where the interface lies. For instance, it's a mix of architectural styles ...
The 3rd International Internet of @ThingsExpo, co-located with the 16th International Cloud Expo - to be held June 9-11, 2015, at the Javits Center in New York City, NY - announces that its Call for Papers is now open. The Internet of Things (IoT) is the biggest idea since the creation of the Worldwide Web more than 20 years ago.
The Internet of Things is tied together with a thin strand that is known as time. Coincidentally, at the core of nearly all data analytics is a timestamp. When working with time series data there are a few core principles that everyone should consider, especially across datasets where time is the common boundary. In his session at Internet of @ThingsExpo, Jim Scott, Director of Enterprise Strategy & Architecture at MapR Technologies, discussed single-value, geo-spatial, and log time series data. By focusing on enterprise applications and the data center, he will use OpenTSDB as an example t...
An entirely new security model is needed for the Internet of Things, or is it? Can we save some old and tested controls for this new and different environment? In his session at @ThingsExpo, New York's at the Javits Center, Davi Ottenheimer, EMC Senior Director of Trust, reviewed hands-on lessons with IoT devices and reveal a new risk balance you might not expect. Davi Ottenheimer, EMC Senior Director of Trust, has more than nineteen years' experience managing global security operations and assessments, including a decade of leading incident response and digital forensics. He is co-author of t...
The Internet of Things will greatly expand the opportunities for data collection and new business models driven off of that data. In her session at @ThingsExpo, Esmeralda Swartz, CMO of MetraTech, discussed how for this to be effective you not only need to have infrastructure and operational models capable of utilizing this new phenomenon, but increasingly service providers will need to convince a skeptical public to participate. Get ready to show them the money!
The Internet of Things will put IT to its ultimate test by creating infinite new opportunities to digitize products and services, generate and analyze new data to improve customer satisfaction, and discover new ways to gain a competitive advantage across nearly every industry. In order to help corporate business units to capitalize on the rapidly evolving IoT opportunities, IT must stand up to a new set of challenges. In his session at @ThingsExpo, Jeff Kaplan, Managing Director of THINKstrategies, will examine why IT must finally fulfill its role in support of its SBUs or face a new round of...
One of the biggest challenges when developing connected devices is identifying user value and delivering it through successful user experiences. In his session at Internet of @ThingsExpo, Mike Kuniavsky, Principal Scientist, Innovation Services at PARC, described an IoT-specific approach to user experience design that combines approaches from interaction design, industrial design and service design to create experiences that go beyond simple connected gadgets to create lasting, multi-device experiences grounded in people's real needs and desires.
Enthusiasm for the Internet of Things has reached an all-time high. In 2013 alone, venture capitalists spent more than $1 billion dollars investing in the IoT space. With "smart" appliances and devices, IoT covers wearable smart devices, cloud services to hardware companies. Nest, a Google company, detects temperatures inside homes and automatically adjusts it by tracking its user's habit. These technologies are quickly developing and with it come challenges such as bridging infrastructure gaps, abiding by privacy concerns and making the concept a reality. These challenges can't be addressed w...
The Domain Name Service (DNS) is one of the most important components in networking infrastructure, enabling users and services to access applications by translating URLs (names) into IP addresses (numbers). Because every icon and URL and all embedded content on a website requires a DNS lookup loading complex sites necessitates hundreds of DNS queries. In addition, as more internet-enabled ‘Things' get connected, people will rely on DNS to name and find their fridges, toasters and toilets. According to a recent IDG Research Services Survey this rate of traffic will only grow. What's driving t...
Connected devices and the Internet of Things are getting significant momentum in 2014. In his session at Internet of @ThingsExpo, Jim Hunter, Chief Scientist & Technology Evangelist at Greenwave Systems, examined three key elements that together will drive mass adoption of the IoT before the end of 2015. The first element is the recent advent of robust open source protocols (like AllJoyn and WebRTC) that facilitate M2M communication. The second is broad availability of flexible, cost-effective storage designed to handle the massive surge in back-end data in a world where timely analytics is e...
Scott Jenson leads a project called The Physical Web within the Chrome team at Google. Project members are working to take the scalability and openness of the web and use it to talk to the exponentially exploding range of smart devices. Nearly every company today working on the IoT comes up with the same basic solution: use my server and you'll be fine. But if we really believe there will be trillions of these devices, that just can't scale. We need a system that is open a scalable and by using the URL as a basic building block, we open this up and get the same resilience that the web enjoys.
We are reaching the end of the beginning with WebRTC, and real systems using this technology have begun to appear. One challenge that faces every WebRTC deployment (in some form or another) is identity management. For example, if you have an existing service – possibly built on a variety of different PaaS/SaaS offerings – and you want to add real-time communications you are faced with a challenge relating to user management, authentication, authorization, and validation. Service providers will want to use their existing identities, but these will have credentials already that are (hopefully) i...
"Matrix is an ambitious open standard and implementation that's set up to break down the fragmentation problems that exist in IP messaging and VoIP communication," explained John Woolf, Technical Evangelist at Matrix, in this SYS-CON.tv interview at @ThingsExpo, held Nov 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA.
P2P RTC will impact the landscape of communications, shifting from traditional telephony style communications models to OTT (Over-The-Top) cloud assisted & PaaS (Platform as a Service) communication services. The P2P shift will impact many areas of our lives, from mobile communication, human interactive web services, RTC and telephony infrastructure, user federation, security and privacy implications, business costs, and scalability. In his session at @ThingsExpo, Robin Raymond, Chief Architect at Hookflash, will walk through the shifting landscape of traditional telephone and voice services ...
Explosive growth in connected devices. Enormous amounts of data for collection and analysis. Critical use of data for split-second decision making and actionable information. All three are factors in making the Internet of Things a reality. Yet, any one factor would have an IT organization pondering its infrastructure strategy. How should your organization enhance its IT framework to enable an Internet of Things implementation? In his session at Internet of @ThingsExpo, James Kirkland, Chief Architect for the Internet of Things and Intelligent Systems at Red Hat, described how to revolutioniz...
Bit6 today issued a challenge to the technology community implementing Web Real Time Communication (WebRTC). To leap beyond WebRTC’s significant limitations and fully leverage its underlying value to accelerate innovation, application developers need to consider the entire communications ecosystem.
The definition of IoT is not new, in fact it’s been around for over a decade. What has changed is the public's awareness that the technology we use on a daily basis has caught up on the vision of an always on, always connected world. If you look into the details of what comprises the IoT, you’ll see that it includes everything from cloud computing, Big Data analytics, “Things,” Web communication, applications, network, storage, etc. It is essentially including everything connected online from hardware to software, or as we like to say, it’s an Internet of many different things. The difference ...
Cloud Expo 2014 TV commercials will feature @ThingsExpo, which was launched in June, 2014 at New York City's Javits Center as the largest 'Internet of Things' event in the world.