JasperReports with Hibernate - Module 2

Continuation of the previous blog .. JasperReports with Hibernate - Module 1


STEP 1: 

    • Install Ireports plugins in Netbeans. Please download the zip file from the below link.
    • JasperReports plugins for Netbeans
    • After its downloaded , just extract the files , you must find 4 files named as below
      • iReport-nb-3.5.2.nbm
      • jasperreports-components-plugin-nb-3.5.2.nbm
      • jasperreports-extensions-plugin-nb-3.5.2.nbm
      • jasperserver-plugin-nb-3.5.2.nbm
    • Now go to your Netbeans IDE,click on Tools menu -> plugins
    • Click on the tab named "Downloaded"
    • Click on the add plugins and browse to the folder where you extracted the .nbm files
    • Below is a screen shot of the above action

    • Select all the .nbm files and install it.Just bypass the security warnings and install it.After Installation is over, restart your Netbeans IDE.
    • Congrats , you have installed this plugin and now we will concentrate on designing Reports using this plugin. 
STEP 2 :

      We are going to give the Report a Hibernate datasource, since we have the hibernate.cfg.xml coded in the previous module, we can provide the same connection to our JasperReports (iReports).To do that please clean and build the project file which we worked out in the previous blog. 

To configure Hibernate with JasperReports , we need to give the classpath informations to the iReport plugin.These class path informations are the package where iReports can find your bean classes, mappings and hibernate.cfg.xml file, database jar file. 

Follow the below steps to accomplish the above said
    • Go to Tools-->Options
    • Click on iReport tab
    • Under iReport tabs, select the "Classpath" tab
    • Click on Add Jar and locate the suitable database jar file. Here i chose sqljdbc.jar for my MSSQL server 2005 database
    • Click on Add Folder and point it to the classes folder which serves as the root for your .java ,  .cfg.xml and .hbm.xml files
    • Check the Reloadable property of both the paths, Click ok and Restart your Netbeans again.
    • Below is the screen shot of the above procedure




STEP 3:

After you restart your Netbeans IDE, click on the "Report Datasources " icon in your tool bar, you can see that icon in the below screenshot marked by an orange line.

    • A window named Connections/Datasources will be opened, click on the New button on the right hand side.
    • Now another window named Datasource will be opened. Select "Hibernate connection" from the list and click next
    • Give the connection a suitable name and click on the Test button to check the connection.





    • You must get a "Connection test successful!" message, else please check the classpaths once again.
    • Save the connection

STEP 4:

          Come back to your StudentReports Project ,Right click on Default package, and create a new "Empty Report file "


    • Give a suitable name to the File and click ok. 
    • A new Report file named StudentReports.jrxml will be opened in an iReport Editor

    • Click on the Report query icon in the Report [ marked by an arrow ]
    • Select Query Language as "Hibernate Query Language" from the drop down list



    • Enter the following query in the query editor
    • "from Student student order by student.department.name asc"

    • The fields of the resulting query will be shown in the right hand side pane.
    • Double click on the Department property and select its name,also select fields firstName,lastName and email
    • Add the selected fields by clicking on the "Add selected field(s)" button
    • You will see the selected fields in the bottom pane
    • Now these are the fields you will be giving as input to your reports
STEP 5:

    • Keep the Report Inspector window and Palette window opened simultaneously as below

    • Expand the Fields icon in the Report Inspector, you will see all the fields to be used in the Report which u chose from the Report Query editor
    • Drag the fields you want to display in the Report into the "Details" band of the Report.
    • Drag some static text fields from the Palette into the "Column header" band and enter the appropriate field's name

    • Click on the Preview button in the Report and you will see something like below.

    • That is all !  Compile the Report and save the .jasper file for Future use

   

In the next blog , i will explain the following
    • Grouping the Records based on some common property
    • Storing generated reports into files
    • Displaying Reports in a browser using servlets

Thanks for Reading this blog!




JasperReports with Hibernate - Module 1

This blog explains you to generate Reports in your Web applications using the 2 Powerful Frameworks in Java Enterprise.
  • Hibernate 3.0
  • Jasper Reports 3.0 
We will see the Entire process of adding objects to database using Hibernate Framework and then listing all the inserted items in Jasper Reports. Lets decide it into 2 Modules

1) Using Hibernate Framework to perform Database operations
2) Using JasperReports to display information from database

Module 1 :
                    I am using Netbeans 6.8 which comes with Hibernate Library.All you have to do it is just include the Hibernate Library in your Project's Library.

STEP 1 :

Create 2 tables  in database "StudentReports". Am using SQL Server 2005,you can use Mysql as well.
  • Department
    • create table Department(ID bigint PRIMARY KEY,name varchar(100) NOT NULL UNIQUE);
  • Student
    • create table Student(ID bigint PRIMARY KEY,firstName varchar(50),lastName varchar(50),email varchar(50) NOT NULL UNIQUE,DepartmentID bigint FOREIGN KEY REFERENCES DEPARTMENT("ID"));






STEP 2 :

After creating the tables in the database, we create 2 Entity classes matching the database tables.Our class files are kept in package com.report.beans

  • Department.java 
  • Student.java






Department.java

package com.report.beans;

public class Department  implements java.io.Serializable {

     private long id;
     private String name;

    public long getId() {
        return this.id;
    }
    
    public void setId(long id) {
        this.id = id;
    }
    public String getName() {
        return this.name;
    }
    
    public void setName(String name) {
        this.name = name;
    }

}







Student.java









package com.report.beans;

public class Student  implements java.io.Serializable {

     private long id;
     private Department department;
     private String firstName;
     private String lastName;
     private String email;

    public long getId() {
        return this.id;
    }  
    public void setId(long id) {
        this.id = id;
    }

    public Department getDepartment() {
        return this.department;
    }    
    public void setDepartment(Department department) {
        this.department = department;
    }

    public String getFirstName() {
        return this.firstName;
    }    
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return this.lastName;
    }    
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
   
    public String getEmail() {
        return this.email;
    }
    public void setEmail(String email) {
        this.email = email;
    }

}







STEP 3 :

After creating the beans , we will create 2 hibernate mapping xml files which acts an interface between the database tables and the java class files.I am putting these files under the package com.report.mappings

Department.java









<hibernate-mapping>
    <class name="com.report.beans.Department" lazy="false" table="Department" schema="dbo" catalog="StudentReports">
        <id name="id" type="long">
            <column name="ID" />
            <generator class="increment" />
        </id>
        <property name="name" type="string">
            <column name="name" length="100" not-null="true" unique="true" />
        </property>
    </class>
</hibernate-mapping>



Student.java









<hibernate-mapping>    
<class name="com.report.beans.Student" lazy="false" table="Student" schema="dbo" catalog="StudentReports">
        <id name="id" type="long">
            <column name="ID" />
            <generator class="increment" />
        </id>
        <many-to-one name="department" class="com.report.beans.Department" fetch="select">
            <column name="DepartmentID" />
        </many-to-one>
        <property name="firstName" type="string">
            <column name="firstName" length="50" />
        </property>
        <property name="lastName" type="string">
            <column name="lastName" length="50" />
        </property>
        <property name="email" type="string">
            <column name="email" length="50" not-null="true" unique="true" />
        </property>
    </class>
</hibernate-mapping>

STEP 4 :

After creating the beans and mapping files, we will create a hibernate configuration file and include the Database credentials and Mapping files. I am placing this configuration file in the default package

hibernate.cfg.xml

<hibernate-configuration>

    <session-factory>

           <property name="hibernate.connection.driver_class">

                    com.microsoft.sqlserver.jdbc.SQLServerDriver
           </property>
           <property name="hibernate.connection.url">

                    jdbc:sqlserver://localhost:1433;databaseName=StudentReports
           </property>
           <property name="hibernate.connection.username">
                    sa
           </property>
           <property name="hibernate.connection.password">
                    sa1@#$
           </property>

           <mapping resource="com/report/mappings/Department.hbm.xml"/>
           <mapping resource="com/report/mappings/Student.hbm.xml"/>

    </session-factory>
</hibernate-configuration>

STEP 6 :

Now i will create 2 data access object files for the 2 Entity bean classes. I will put these file in the package com.reports.dao

DepartmentDAO.java

package com.report.dao;

import com.report.beans.Department;
import org.hibernate.Session;


import org.hibernate.Criteria;
import org.hibernate.criterion.Expression;







import java.util.ArrayList;


public class DepartmentDAO{

    public String saveDepartment(Department department)
    {
        Session session = HibernateSessionFactory.getSession();
        String Result = "";

        try
        {
            session.beginTransaction();
            session.save(department);
            session.getTransaction().commit();
            session.close();
            Result = "Department Saved Successfully";
        }
        catch(Exception e)
        {
            e.printStackTrace();
            session.close();
            Result = "Department was not saved due to the above Exception";
        }

        return Result;
    }



    public Department getDepartmentByName(String name)
    {
        Department department = new Department();

        Session session = HibernateSessionFactory.getSession();
        Criteria criteria = session.createCriteria(Department.class);
            criteria.add(Expression.eq("name", name));

        ArrayList listOfMatchingDepartments = (ArrayList)criteria.list();
       
        if(listOfMatchingDepartments.size()==1)
            department = listOfMatchingDepartments.get(0);

        return department;
    }

}

StudentDAO.java

package com.report.dao;

import com.report.beans.Student;
import org.hibernate.Session;

public class StudentDAO{

    public String saveStudent(Student student)
    {
        Session session = HibernateSessionFactory.getSession();
        String Result = "";

        try
        {
            session.beginTransaction();
            session.save(student);
            session.getTransaction().commit();
            session.close();
            Result = "Student Saved Successfully";
        }
        catch(Exception e)
        {
            e.printStackTrace();
            session.close();
            Result = "Student was not saved due to the above Exception";
        }

        return Result;
    }

}

STEP 7 :

Create your Main class files from which you will start inserting objects into databases, i am placing these files in the package com.report.test

AddDepartments.java

package com.report.test;

import com.report.beans.Department;
import com.report.dao.DepartmentDAO;

public class AddDepartments
{
    public static void main(String args[])
    {
        Department electronics = new Department();
            electronics.setName("Electronics Engineering");

        Department computerScience = new Department();
            computerScience.setName("Computer science Engineering");

        Department civil = new Department();
            civil.setName("Civil Engineering");


        String Result1 = new DepartmentDAO().saveDepartment(electronics);
            System.out.println(Result1);

        String Result2 = new DepartmentDAO().saveDepartment(computerScience);
            System.out.println(Result2);
        
        String Result3 = new DepartmentDAO().saveDepartment(civil);
            System.out.println(Result3);
    }
}

AddStudents.java


package com.report.test;

import com.report.beans.Department;
import com.report.beans.Student;
import com.report.dao.DepartmentDAO;
import com.report.dao.StudentDAO;

public class AddStudents
{
    public static void main(String args[])
    {
        Student student1 = new Student();
            student1.setFirstName("John");
            student1.setLastName("Mathew");
            student1.setEmail("john@abc.com");

        Department department = new DepartmentDAO().getDepartmentByName("Computer science Engineering");
            student1.setDepartment(department);


        String Result = new StudentDAO().saveStudent(student1);
        System.out.println(Result);

    }
}







STEP 8 :

Now your Database Tables will be populated with the objects that you added. Below my are database tables

Departments Table
----------------------------------------
ID    |    Name    
----------------------------------------
1      |    Electronics Engineering
2      |    Computer science Engineering
3      |    Civil Engineering
----------------------------------------








StudentsTable
-----------------------------------------------------------------------------------
ID  |  FirstName     | LastName    |      Email                |     DepartmentID
-----------------------------------------------------------------------------------






1JohnMathewjohn@abc.com2
2RobertLangtonrobert@abc.com1
3GillChristgchrist@abc.com1
4MichaelJonesmjones@abc.com1
5TomHankshanks@abc.com1
6SteveWaughsteve@abc.com3
7BrianAdamsbrian@abc.com3
8BillGuarnerebill@abc.com3
9BuckComptonscompton@abc.com3
10CarwoodLiptonlipton@abc.com2
11RichardWinterswinters@abc.com2
-----------------------------------------------------------------------------

Was this Blog Helpful?