Hibernate Framework is an Object/Relational Mapping (ORM) solution for Java environments. The framework simplifies the mapping of data between an object model representation and a relational data model representation. Hibernate maps Java classes to corresponding database tables by providing common data persistence-related programming tasks. This helps to simplify the code needed to establish connectivity.

Structural details of the Hibernate Framework

The basic structure of the Hibernate Framework is made up of the following categories of files:
    The persistent class: Includes a class that corresponds to an entity table in a database. Instances of this class will be used to represent the entries in that table. The class should, therefore, be created with the corresponding getter() and setter() methods so that it can carry the data. The mapping file: Includes details about the mapping between 1: classes and tables 2: instance variables and columns of the table. The configurations file: Includes details that give Hibernate relevant information about the database and how connections with the database can be managed. This information can be provided via an XML file, a properties file, or even programmatically. In our sample here, we will be using an XML file to provide this information. The testing class: Uses class details from the persistent class file, the mapping details from the mapping file, and the connectivity details from the configurations file for storing and retrieving data from the database.

FusionCharts JSP Wrapper

In addition to several other features, FusionCharts Suite XT comes with the FusionCharts JSP wrapper that lets you create interactive, data-driven charts without writing any JavaScript code. The server-side wrapper generates the required JavaScript and HTML code as a string, which is used to render charts in a browser. In this blog sample, we will be using the FusionCharts JSP Wrapper within our JSP page to configure the chart and render it using JAVA code in the scriptlet tags. Click here to know more about the FusionCharts JSP wrapper.

Requirements:

Before we start talking about the procedure for rendering a chart using the Hibernate Framework, ensure that you:
    Download the Hibernate Jars. Download FusionCharts Suite XT. Download the FusionCharts JSP wrapper.

Steps for rendering a chart using Hibernate Framework by fetching data from the database

Step 1

To create a web project, from the File menu, click New, and select Dynamic Web Project. The New Dynamic Web Project dialog box opens.

Step 2

  • Enter the relevant project details in the New Dynamic Web Project dialog box.
  • From the Target runtime drop-down, select a preconfigured local web server. For the sample created in this article, we will be using Apache Tomcat 8.
  • After filling all details, click Finish.
A new project, named FCHibernateProject is created.

Step 3

To include the required external Hibernate Jars in your project:
  • Right click the FCHibernateProject in the Project Explorer.
  • From the menu rendered, select Properties.
  • The Properties for FCHibernateProject dialog box opens.
  • From the Properties for FCHibernateProject dialog box, select the Java Build Path filter.
  • Open the Libraries tab.
  • Click Add External Jars and add the path for the downloaded Hibernate Jars.
External Jars for the Hibernate Framework are added to the Eclipse project.

Step 4

To enable database connectivity, you need to add connector jars corresponding to the database you are using. The sample created in this article uses the MySql database, so mysql-connector.jar has to be included in the project. You also need to include the GSON.jar in order to retrieve the string containing the JSON representation of the data in an array. GSON is a Java library that is used to convert:
  • Java objects into their corresponding JSON representation
  • JSON strings into their corresponding Java objects
The GSON and the mysql-connector.jar files are available in the includeJarFiles folder of the downloaded package for the FusionCharts JSP wrapper. To access the includeJarFiles folder, follow the steps outlined in Step 3.

Step 5

  • From the Project Explorer, in the FCHibernateProject folder, right click the src subfolder.
  • From the menu rendered, click NewPackage
  • The New Java Package dialog box opens.
  • Create a package named fusioncharts to save the FusionCharts.java wrapper file.
  • Click Finish.
  • Save the FusionCharts JSP Wrapper in the created package.

Step 6

Copy the FusionCharts JavaScript files from the downloaded FusionCharts Suite XT package and paste them in the WebContent folder of the FCHibernateProject.

Step 7

Create a database in MySQL with the data for rendering a single-series column chart. A reference image for the required table structure is given below: The values entered in the database table will be fetched and provided to the FusionCharts constructor for rendering the chart.

Step 8

Next, you need to create a persistent class to have a class that corresponds to each entity table in the database. Instances of this class will be used to represent the entries in each table of the database. The persistent class, named FusionData.java in this sample, contains the corresponding instance variables for the fields of the database table, along with the setter() and getter() methods for the respective variables. To create the persistent class: Create a .java file, FusionData.java, and save it in the fetchdata package. Copy the following code and paste it in the FusionData.java file:
package fetchdata;

public class FusionData {

      private int ID;
      private String labelData;
      private String valueData;
    
      public int getID() {
        return ID;
      }
      public void setID(int id) {
        ID = id;
      }

      public String getLabelData() {
      return labelData;
    }
    public void setLabelData(String newlabel) {
      this.labelData = newlabel;
    }

    public String getValueData() {
      return valueData;
    }
    public void setValueData(String newvalue) {
      this.valueData = newvalue;
    }    
}

Step 9

You also need to create a Java class that creates a session, runs a query, and returns a record-set as a list via a function call. This class will be used in the JSP page to fetch data for rendering the chart. To create this Java class: Create a .java file, SimpleChart.java, and save it in the fetchdata package Copy the following code and paste it in the SimpleChart.java file:
package fetchdata;
import java.util.Iterator;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

public class SimpleChart {


	public List<FusionData> getListData(){
		
	    SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
	    Session session = sessionFactory.openSession();
	    Transaction tx = session.beginTransaction();

                List<FusionData> entireData = session.createQuery("FROM FusionData").list();
        
                tx.commit();
       
                session.close(); 
        
                return entireData;

            }
}
The records returned by the Java class are stored in the FusionData list.

Step 10

You now need a mapping file to map the data in the FusionData list with the data in the singleseriestable database table. To do this:
  • From the Project Explorer, in the FCHibernateProject folder, right click the src subfolder.
  • From the menu rendered, select NewOthers.
  • The New dialog box opens.
  • In the New dialog box, select XML File to set the type of the file to be created.
  • Click Next. The New XML File dialog box opens.
  • In the New XML File dialog box, set the path of the folder in which the file will be saved in the Enter or select the parent folder field. For our sample, we will set it to FCHibernate/src. In the File name field, enter the filename. For our sample, we’ll name the file FusionData.hbm.xml.
  • Click Finish.
The modified directory structure, after the FusionData.hbm.xml file is created. Copy the following code and paste it in the FusionData.hbm.xml file:
<?xml version="1.0"?>
              <!DOCTYPE hibernate-mapping PUBLIC
              "-//Hibernate/Hibernate Mapping DTD//EN"
              "https://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
              
              <hibernate-mapping>
              
                <class name="fetchdata.FusionData" table="singleseriestabl">
                
                    <id name="ID" type="int">
                          <generator class="increment"/>
                    </id>
                    
                   	<property name="labelData" column="label" type="string"/>
                    <property name="valueData" column="value" type="string"/>
                    
                </class>
                
              </hibernate-mapping>

Step 11

Follow the steps in Step 10 to create the hibernate.cfg.xml file for the Hibernate configurations. This file includes database-related information like the connection URL, the connection username and password, the connection driver, and the mapping resource. The modified directory structure, after this file is created, looks as shown in the image below: Copy the following code and paste it in the hibernate.cfg.xml file:
<?xml version='1.0' encoding='UTF-8'?>
              <!DOCTYPE hibernate-configuration PUBLIC
              "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
              "https://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

              <hibernate-configuration>

              <session-factory>

                  <!-- ________________ To be Edited _________________ -->

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

                  <!-- _____________ End of To be Edited ______________ -->

              
                  <property name="connection.driver_class">
                          com.mysql.jdbc.Driver
                  </property>
                  <property name="dialect">
                          org.hibernate.dialect.SQLServerDialect
                  </property>
                  <property name="current_session_context_class">thread</property>

              
                  <!-- _________ Defining the Mapping Files ___________ -->

                  <mapping resource="FusionData.hbm.xml" />

              </session-factory>
              </hibernate-configuration>
Note: In the above code, replace the jdbc_URL, jdbc_Username, and jdbc_Password variables with their appropriate values.

Step 12

Finally, you need a JSP file that contains the chart container to render the chart. This file will also include the JSP tags along with the scripts and the Java code needed to import the JS files and Java classes for fetching data from the database. To do this: Create a .jsp fle, TryChart.jsp, and save it in the WebContent folder. Copy the following code and paste it in the TryChart.jsp file:
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@page import="java.sql.*" %>
<%@page import="java.util.*" %>
<%@page import="com.google.gson.*" %>

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Creating Charts with Data from a Database - fusioncharts.com</title>

        <script type="text/javascript" src="fusioncharts.js"></script>
        <script type="text/javascript" src="fusioncharts.charts.js"></script>
    <script type="text/javascript" src="fusioncharts.theme.zune.js"></script>
    </head>
    <body>
         <div id="chart"></div>

        <%@page import="fusioncharts.FusionCharts" %>
        <%@page import="fetchdata.SimpleChart" %>
        <%@page import="fetchdata.FusionData" %>
      
        <%
			
			//creating Map for storing chart dataSource kwy-value pairs
			Map<String, String> chartobj = new HashMap<String, String>();
	        
	        chartobj.put("caption", "Top 10 countries winning Gold medals");
	        chartobj.put("subcaption", "Rio Olympics 2016");
	        chartobj.put("yAxisName", "Medals won");
	        chartobj.put("paletteColors", "#3a4660");
	        chartobj.put("captionFontColor", "#3a4660");
	        chartobj.put("subCaptionFontColor", "#3a4660");
	        chartobj.put("labelFontColor", "#3a4660");
	        chartobj.put("yAxisNameFontColor", "#3a4660");
	        chartobj.put("placevaluesInside", "1");
	        chartobj.put("rotatevalues", "0");
	        chartobj.put("usePlotGradientColor", "0");
	        chartobj.put("theme", "zune");
		    
	        //loop counter
			int i = 0;
	        
	        //creating ArrayList Collections object to store the data of the chart
			ArrayList arrData = new ArrayList();
			
			//creating object reference for Hibernate class "SimpleChart" to connect DB and fetch data
			SimpleChart myData = new SimpleChart();
			
        	//calling getListData() method using Hibernate class object "myData" to recieve
        	//as a List Collections object
			List<FusionData> dataList = myData.getListData();
			
			//System.out.println("Accessing in JSP : " + dataList.get(0).getValueData());
			
			//iterating the List object to store in the "arrData" ArrayList object
			while(i != dataList.size()) {
	            Map<String, String> lv = new HashMap<String, String>();
	            lv.put("label", dataList.get(i).getLabelData());
	            lv.put("value", dataList.get(i).getValueData());
	            arrData.add(lv); 
	            i++;
	        }
			
			//System.out.println("Accessing after fetching : " + arrData);
			
			//create 'dataMap' map object to make a complete FC datasource.
	        Map<String, String> dataMap = new LinkedHashMap<String, String>();
			
			
			//create 'Gson' object
	        Gson gson = new Gson();
			
		   /*  gson.toJson() the data to retrieve the string containing the
		       JSON representation of the data in the array.
		   */
	        dataMap.put("chart", gson.toJson(chartobj));
	        dataMap.put("data", gson.toJson(arrData));
	        			
			//creating FC instance using FusionCharts JSP wrapper
	       	FusionCharts columnChart= new FusionCharts(
	       			"column2d",				//type of chart
	                   "myChart",				//unique chart ID
	                   "740","470",			//width and height of the chart
	                   "chart",				//div ID of the chart container
	                   "json",					//data format
	                   gson.toJson(dataMap) 	//data source
	        );
           
            %>
            
            <!--    Step 5: Render the chart    -->                
            <%=columnChart.render()%>
           
        
    </body>
</html>
After execution, your output should look as shown in the image below: If you have trouble executing, you can download this sample from here.

Take your data visualization to a whole new level

From column to donut and radar to gantt, FusionCharts provides with over 100+ interactive charts & 2,000+ data-driven maps to make your dashboards and reports more insightful

Explore FusionCharts

Leave a comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.