birt with hibernate

14
BIRT with Hibernate Overview BIRT is an Eclipse-based open source reporting platform for web applications, especially those based on Java and J2EE. The intent of this example is to demonstrate data retrieval using BIRT Scripted Data Source functionality to access Hibernate POJOs (Plain Old Java Objects) that are persisted to a MySQL database. The integration is achieved by wrapping java calls to the Hibernate objects. The Hibernate sections of the example are based on the Hibernate tutorials, which can be accessed at http://www.hibernate.org. Problem Description Classic Models Corporation, a retailer of scale models of classic cars and other vehicles, has decided to bridge the object-relational gap. The motivation for this is the maintenance costs associated with the many objects that have been created to automate their intranet and Internet presence. The code base for persisting all of these objects has become quite large and difficult to maintain and tune. Problem Solution Classic Models has decided to use Hibernate for persisting their objects to a MySQL backend. The objects will not be moved all at once. Classic Models will use a staged approach, converting tables to Java classes and reporting off of the newly created classes. The company already uses BIRT for all reporting needs, and will change the XML report designs while they are upgrading their infrastructure. The company’s “classicmodels” database provides a simple set of tables and data that form the basis for a number BIRT sample reports, and is included in a Derby implmentation in the BIRT framework download. The scripts for creating a MySQL version of the database are also available for download on the BIRT website (http://www.eclipse.org/birt). To begin this example, we will convert the Customer table from the database over to Hibernate. A portion of the converted class is shown below. public class Customer { private int customerNumber; private String customerName; private String contactLastName; private String contactFirstName; private String phone; private String addressLine1; private String addressLine2; private String city; private String state; private String postalCode; private String country; private Integer salesRepEmployeeNumber; private double creditLimit; /** * */ public Customer() { super(); } public String getAddressLine1() {

Upload: ruthless-man

Post on 14-Oct-2014

333 views

Category:

Documents


6 download

TRANSCRIPT

Page 1: BIRT With Hibernate

BIRT with Hibernate

OverviewBIRT is an Eclipse-based open source reporting platform for web applications, especially those based on Java and J2EE.

The intent of this example is to demonstrate data retrieval using BIRT Scripted Data Source functionality to access Hibernate POJOs (Plain Old Java Objects) that are persisted to a MySQL database. The integration is achieved by wrapping java calls to the Hibernate objects. The Hibernate sections of the example are based on the Hibernate tutorials, which can be accessed at http://www.hibernate.org.

Problem DescriptionClassic Models Corporation, a retailer of scale models of classic cars and other vehicles, has decided to bridge the object-relational gap. The motivation for this is the maintenance costs associated with the many objects that have been created to automate their intranet and Internet presence. The code base for persisting all of these objects has become quite large and difficult to maintain and tune.

Problem SolutionClassic Models has decided to use Hibernate for persisting their objects to a MySQL backend. The objects will not be moved all at once. Classic Models will use a staged approach, converting tables to Java classes and reporting off of the newly created classes. The company already uses BIRT for all reporting needs, and will change the XML report designs while they are upgrading their infrastructure. The company’s “classicmodels” database provides a simple set of tables and data that form the basis for a number BIRT sample reports, and is included in a Derby implmentation in the BIRT framework download. The scripts for creating a MySQL version of the database are also available for download on the BIRT website (http://www.eclipse.org/birt). To begin this example, we will convert the Customer table from the database over to Hibernate. A portion of the converted class is shown below.

public class Customer {

private int customerNumber; private String customerName; private String contactLastName; private String contactFirstName; private String phone; private String addressLine1; private String addressLine2; private String city; private String state; private String postalCode; private String country; private Integer salesRepEmployeeNumber; private double creditLimit;

/** * */public Customer() {

super();}

public String getAddressLine1() {

Page 2: BIRT With Hibernate

return addressLine1;}

public void setAddressLine1(String addressLine1) {this.addressLine1 = addressLine1;

}

.

.

.

After completing the Customer class, we will need to build the mapping file for Hibernate. See the Hibernate tutorials and documentation for more details. The mapping file is listed below.

<?xml version="1.0"?><!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="org.eclipse.birt.samples.scripted.hibernate"> <class name="Customer" table="customers"> <id name="customerNumber" column="customerNumber" type="integer"> <generator class="native"/> </id> <property name="customerName" column="customerName" type="string"

not-null="true" /> <property name="contactLastName" column="contactLastName" type="string"

not-null="true" /> <property name="contactFirstName" column="contactFirstName" type="string"

not-null="true" /> <property name="phone" column="phone" type="string" not-null="true" /> <property name="addressLine1" column="addressLine1" type="string"

not-null="true" /> <property name="addressLine2" column="addressLine2" type="string" /> <property name="city" column="city" type="string" not-null="true" /> <property name="state" column="state" type="string" /> <property name="postalCode" column="postalCode" type="string" /> <property name="country" column="country" type="string" not-null="true" /> <property name="salesRepEmployeeNumber" column="salesRepEmployeeNumber" type="integer"/> <property name="creditLimit" column="creditLimit" type="double" /> </class>

</hibernate-mapping>

This mapping file will use a table in the classicmodels database named “customers”. This table contains properties for the customers of Classic Models.

The next step is to create a Hibernate configuration file that points to the instance of MySQL. Again, see the Hibernate documentation for definitions of the fields used.

<?xml version='1.0' encoding='utf-8'?><!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

<session-factory>

<!-- Database connection settings --> <property name="connection.driver_class">com.mysql.jdbc.Driver</property> <property

Page 3: BIRT With Hibernate

name="connection.url">jdbc:mysql://localhost:3306/classicmodels</property> <property name="connection.username">root</property> <property name="connection.password">sa</property>

<!-- JDBC connection pool (use the built-in) --> <property name="connection.pool_size">1</property>

<!-- SQL dialect --> <property name="dialect">org.hibernate.dialect.HSQLDialect</property>

<!-- Echo all executed SQL to stdout --> <property name="show_sql">true</property>

<!-- Drop and re-create the database schema on startup --> <!-- <property name="hbm2ddl.auto">create</property> -->

<mapping resource="Customer.hbm.xml"/> </session-factory>

</hibernate-configuration>

If you look at the highlighted connection.url property, you will see the information that we are using to connect to the instance of MySQL. The highlighted mapping resource entry points to the Customer mapping file we created earlier.

Configuration of the Customer class persistence is now complete. Next, we need some method of adding and displaying instances of Customer. In this example, we will only require read access to these objects so we have decided to use a simple POJO to list Customers.

The POJO will be named CustomerList for reasons that should become apparent. This class will have one method (other than main) that retrieves the Customers through Hibernate and returns them in a List object. This method is displayed below.

This example uses the HibernateUtil class supplied with the Hibernate tutorial. //method for listing customers//Notice it takes an hql String as a parameter

public List listCustomers(String hql) {

Session hibsession = HibernateUtil.currentSession();

Transaction trans = hibsession.beginTransaction();

List result = hibsession.createQuery(hql).list();

trans.commit(); HibernateUtil.closeSession();

return result;}

You will notice that we are using the HibernateUtil class that is developed and illustrated in the Hibernate tutorial for handling sessions with Hibernate. See http://www.hibernate.org for details.

In the listCustomers method we are creating an HQL query that will return a list of the Customers. The actual HQL statement will be passed in from BIRT and will be described later in this article.

Page 4: BIRT With Hibernate

After building the sample, we run a Customer listing as shown below. We then wrap up the code into birtSamples.jar.

… [java] ================================================= [java] Customer: Raanan Stores, Inc [java] Contact First Name: Raanan [java] Contact Last Name: Altagar,G M [java] phone: + 972 9 959 8555 [java] address line 1: 3 Hagalim Blv. [java] address line 2: null [java] City: Herzlia [java] State: null [java] Postal Code: 47625 [java] Country: Israel [java] credit limit: 0.0

BIRT PresentationNext we will illustrate how to “read” these Customer hibernate objects from within BIRT. To do this, we will use BIRT’s Scripted Data Source functionality to access the CustomerList POJO created in the previous section.

The first thing we need to do is copy the Hibernate, jdbc and birtSamples jar files to the appropriate directory within BIRT. Below are the full list of required jar files and the location to which they are copied. The target directory will depend on where you have installed Eclipse.

antlr-2.7.5H3.jarasm-attrs.jarasm.jarcglib-2.1.jarcommons-collections-2.1.1.jarcommons-logging-1.0.4.jardom4j-1.6.jarehcache-1.1.jarhibernate3.jarjta.jarlog4j-1.2.9.jarmysql-connector-java-3.1.10-bin.jarbirtSamples.jar

C:\eclipse3.1\eclipse\plugins\org.eclipse.birt.report.viewer_1.0.1\birt\WEB-INF\lib

We also copy the Hibernate configuration files, shown below, to the appropriate directory.

hibernate.cfg.xmlCustomer.hbm.xml

C:\eclipse3.1\eclipse\plugins\org.eclipse.birt.report.viewer_1.0.1\birt\WEB-INF\classes

BIRT should now have access to the objects we created.

Page 5: BIRT With Hibernate

Because we are upgrading Classic Models systems using a staged approach, we will be modifying an existing BIRT report—the “Corporation” report. This sample report is located in the \eclipse\plugins\org.eclipse.birt.report.designer.ui_1.0.1\sampleReports\RptDesign\ directory of the BIRT install. It lists the Classic Models offices, showning the employees based in each office and the customers they are responsible for handling. Here is one page of output from the report.

This report has one Data Source, and three Datasets. The Data Source points to the default classicmodels Derby Database included in the BIRT distribution.The third Data Set, represented below, queries the Customers table directly.

Page 6: BIRT With Hibernate

This query is bound to the last Table in the report (shown selected in the illustration below) and is used for displaying customers that are not currently assigned to any Classic Model Corporation employee.

Now that we have the report open, we are ready to do some modifications to include our Hibernate example. First, we add a new Data Source. This can be done by selecting thedata explorer tab and right clicking on Data Source. Select New Data Source next.

Page 7: BIRT With Hibernate

The following wizard is displayed.

Select Scripted Data Source and name it Hibernate. Then right click on the Data Sets and select New Data Set.

Page 8: BIRT With Hibernate

The Data Set wizard displays and we name the new Data Set Hibernate_st.

The Hibernate_st Data Set will show up in the Data Explorer tab and we can double click it to display its configuration. Then we enter all the columns that represent values from the Customer class developed earlier.

Page 9: BIRT With Hibernate

The Preview Results function in the Data Set is not enabled for Scripted Data Sources, but we will be able to see the data when we preview the report.

Now we move on to the actual scripting required for the Scripted Data Source. Right click the data set and select edit code.

Page 10: BIRT With Hibernate

The script editor opens and lists the methods in a drop down box.

The methods we will be concerned with for this example are the open, fetch and close methods.By filling in those methods, we instantiate a CustomerList instance, call its listCustomers method and iterate through the returned List, building a row of data for each Customer.

First, we enter the following code in the Open method, which is called once when the Data Set is opened.

Page 11: BIRT With Hibernate

The first line instantiates the CustomerList class. The next line calls the listCustomer method, passing an HQL statement, which returns a List. This List is stored in the customers variable. Next we create an iterator based on the returned List. For the present, we have commented out the line of code containing the where clause on the HQL statement. This will be discussed later.

We now have our customers and can set our row values accordingly. Select the dropdown list and choose the fetch method and enter the following code.

For a Scripted Data Source, the fetch method is called until a false is returned. That is why we check to see if we have iterated through all the results before setting the row values.

Next we set the local customer variable to the next item in the iterator. This customer is an instance of the Customer class. We then set the row’s values using the getter methods for the Customer object.

The final method that needs code is the close method. Choose the close method from the drop down list and enter the following code.

Page 12: BIRT With Hibernate

This code is used for closing the Hibernate session factory and setting used variables to null. The Scripted Data Source is now essentially complete. Using the Data Set throughout the remainder of the report is no different than using any other BIRT report Data Set.

We select the last Table element and click on the Property Editor. Next select the binding tab and change the Data Set from Data Set2 to Hibernate_st.

We should now be able to preview the results.

Page 13: BIRT With Hibernate

You will notice that every customer is coming back as Unassigned. The reason for this is that the original Data Set has an output filter on the Data Set.

We have two options now. We can place this same filter on our new Data Set or we can modify our HQL statement and achieve the same results.Modify the HQL by uncommenting the line with the where clause as shown below and run the report.

Page 14: BIRT With Hibernate

The output of the report now looks correct.

Following ThroughTo find out more information about BIRT, visit our site at http://www.eclipse.org/birt.Future BIRT example articles will cover deploying the application to JBoss, Tomcat and possibly Spring.