JAVA JSP Hibernate Step By Step Tutorial With Oracle Database

By | November 17, 2014

In this step by step JAVA tutorial, I am going to explain in details how to create a MVC (Model View Controller) based web application in JAVA using JSP as front end technology, Hibernate technology for persistence at Model Layer to store data to and fetch data from Oracle database, Servlets as Controllers and JAVA classes based business services for business logic implementation.

Application Scenario:

To explain how to develop MVC based web application in JAVA, I am taking a very simple scenario here for Account Management System with below use cases:

1. User Can Add New Account by adding account related information through a Web Form

2. User can Search for any account information through a search form.

 

Technologies Used:

  • Oracle as back-end database.
  • JSP as front end view technology to create User Interface.
  • Hibernate as ORM (Object Relational Mapping) technology.
  • JAVA Servlets as Controllers.
  • JAVA Classes for business Services implementation
  • Netbeans as IDE.
  • Glass Fish as application server.

 

Steps to create JSP, Hibernate Web Application

Step 1: Create JAVA Web Application Project

In Netbeans IDE, go to File Menu and choose New Project option.  In the Categories, choose Java Web and Web Application in the projects options.

netbeans create new java web project

 

Click on the Next button and specify Project Name and Location as shown in the screenshot below:

java netbeans project name and location

Click Next button and now select the server. I have Glass Fish Server already installed so I am using that. You can add a new server if you want by clicking on Add button.

Also select Java EE Version for your application.

java web application server setting

 

Click on Next button and now choose Hibernate from the list of frameworks.  Once you check Hibernate in the framework list, Hibernate Configuration options appear. If you have already created a database connection, simply choose that. Otherwise, use New Database Connection option to create a new connection.

In my case, I have already created database connection to Oracle and I am simply choosing the connection from the drop down list as shown in screenshot below:

netbeans select hibernate framework and choose oracle database

 

Now just click on the Finish button. This completes our first step of creating Java Web Application project in Netbeans IDE.

You will notice that Hibernate Configuration file (hibernate.cfg.xml) will be created in your project Source Packages with configuration details like below:

<?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>
    <property name="hibernate.dialect">org.hibernate.dialect.OracleDialect</property>
    <property name="hibernate.connection.driver_class">oracle.jdbc.OracleDriver</property>
    <property name="hibernate.connection.url">jdbc:oracle:thin:@localhost:1521:XE</property>
    <property name="hibernate.connection.username">SYSTEM</property>
    <property name="hibernate.connection.password">admin</property>
    <mapping resource="Model/TblAccount.hbm.xml"/>
  </session-factory>
</hibernate-configuration>

Step 2: Prepare database for Application

For simple Account Management Scenario, we are going to have only one database table TBL_ACCOUNT which will store account related information. Use below sql query to create the table in database:

create table TBL_ACCOUNT
(
ACCOUNT_ID          NUMBER,
ACCOUNT_BALANCE     NUMBER,
ACCOUNT_BENEFICIARY VARCHAR2(30),
ACCOUNT_TYPE        VARCHAR2(10)
)

 

Step 3: Create Hibernate Utility Class, Hibernate Configurations, POJOs and Mapping Files

In this step, we will work on Model Layer of our application in which we will create Hibernate Reverse Engineering (reveng) file and then using this file, we will create POJO and Hibernate Mapping XML file based on our database table TBL_ACCOUNT

Create a new Package inside Source Packages of your project and name it as Model. Now Right Click on this Package Name and then by going to New–>Other, select Hibernate from the Category and then Hibernate Reverse Engineering Wizard from the File Type options as shown in below screenshot:

java hibernate reverse engineering wizard

In the next screen you will be asked to give a name to this file. After that click Next button again.  Now application will connect to the database and will retrieve list of all available tables from the chosen schema. Choose the table TBL_ACCOUNT and then use Add button to move it to Selected Tables List. (Please note that Table Must have a Primary Key otherwise It won’t be available to be added).

hibernate reverse engineering wizard add table

 

A new file with the name Hibernate.reveng.xml will be created in the Model package with below configurations:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-reverse-engineering PUBLIC "-//Hibernate/Hibernate Reverse Engineering DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-reverse-engineering-3.0.dtd">
<hibernate-reverse-engineering>
  <schema-selection match-schema="SYSTEM"/>
  <table-filter match-name="TBL_ACCOUNT"/>
</hibernate-reverse-engineering>

 

Now we need to create POJO and mapping file (hbm.xml) based on the database table TBL_ACCOUNT

For this purpose, right click on Model Package and choose Other–>Hibernate–>Hibernate Mapping Files and POJOs from Database option as shown below:

hibernate mapping files and pojo from database table

Click Next and then choose Hibernate Configuration File, Reverse Engineering File and then click Finsih.

A new hibernate mapping file (TblAccount.hbm.xml) is created as shown 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">
<!-- Generated Nov 17, 2014 9:32:00 PM by Hibernate Tools 3.2.1.GA -->
<hibernate-mapping>
    <class name="Model.TblAccount" table="TBL_ACCOUNT" schema="SYSTEM">
        <id name="accountId" type="integer">
            <column name="ACCOUNT_ID" precision="22" scale="0" />
            <generator class="assigned" />
        </id>
        <property name="accountBalance" type="integer">
            <column name="ACCOUNT_BALANCE" precision="22" scale="0" />
        </property>
        <property name="accountBeneficiary" type="string">
            <column name="ACCOUNT_BENEFICIARY" length="30" />
        </property>
        <property name="accountType" type="string">
            <column name="ACCOUNT_TYPE" length="10" />
        </property>
    </class>
</hibernate-mapping>

Similarly, POJO class with the name TblAccount.java has also been created based on the columns of database table. POJO class contains all the properties along with their Getter and Setter methods as shown below:

package Model;
// Generated Nov 17, 2014 9:31:58 PM by Hibernate Tools 3.2.1.GA
 
 
import java.math.*;
 
/**
 * TblAccount generated by hbm2java
 */
public class TblAccount  implements java.io.Serializable {
 
 
     private int accountId;
     private int accountBalance;
     private String accountBeneficiary;
     private String accountType;
 
    public TblAccount() {
    }
 
 
    public TblAccount(int accountId) {
        this.accountId = accountId;
    }
    public TblAccount(int accountId, int accountBalance, String accountBeneficiary, String accountType) {
       this.accountId = accountId;
       this.accountBalance = accountBalance;
       this.accountBeneficiary = accountBeneficiary;
       this.accountType = accountType;
    }
 
    public int getAccountId() {
        return this.accountId;
    }
 
    public void setAccountId(int accountId) {
        this.accountId = accountId;
    }
    public int getAccountBalance() {
        return this.accountBalance;
    }
 
    public void setAccountBalance(int accountBalance) {
        this.accountBalance = accountBalance;
    }
    public String getAccountBeneficiary() {
        return this.accountBeneficiary;
    }
 
    public void setAccountBeneficiary(String accountBeneficiary) {
        this.accountBeneficiary = accountBeneficiary;
    }
    public String getAccountType() {
        return this.accountType;
    }
 
    public void setAccountType(String accountType) {
        this.accountType = accountType;
    }
 
 
 
 
}

 

Now we need to create a Utility class for hibernate session handling. For this purpose, create a new package and name it as Util. Now right click on this package and then choose Other–>Hibernate–>HibernateUtil.java to crate a new utility file.

A new class with the name NewHibernateUtil.java is created with session related code as shown below:

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Util;
 
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.SessionFactory;
 
/**
 * Hibernate Utility class with a convenient method to get Session Factory
 * object.
 *
 * @author Administrator
 */
public class NewHibernateUtil {
 
    private static final SessionFactory sessionFactory;
 
    static {
        try {
            // Create the SessionFactory from standard (hibernate.cfg.xml) 
            // config file.
            sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
        } catch (Throwable ex) {
            // Log the exception. 
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }
 
    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }
}

 

Step 4: Implement Business Logic in Business Services

In this step, we will create a class with the name AccountService.java and will implement business logic for account query and account addition in it.

Crate a new package and name it as BusinessServices. Create a new Java Class AccountService.java in the package.

In this class implement following two methods:

1. addAccount method to persist (save) account object in database table using hibernate.

2. searchAccount method to fetch account information from database table using hibernate.

Code of this service is shown below:

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package BusinessServices;
import org.hibernate.Transaction;
import org.hibernate.Session;
import Model.TblAccount;
import Util.NewHibernateUtil;
import com.sun.tools.xjc.reader.xmlschema.bindinfo.BIConversion.User;
import org.hibernate.Query;
/**
 *
 * @author Administrator
 */
public class AccountService {
 
    public String addAccount(TblAccount acc)
    {
         String message=null;
        Session s=null;
        try
        {
            s=NewHibernateUtil.getSessionFactory().openSession();
            Transaction tr=s.getTransaction();
           tr.begin();
          s.save(acc);
          tr.commit();
                message="Saved Data";  
           return message; 
        }
        catch (Exception e)
        {
            return (e.getMessage());
        }
        finally 
                {
                    s.close();
                }
 
 
    }
    public TblAccount searchAccount(String pi_Id)
    {
          String message=null;
        Session session=null;
       Transaction tx = null;
	 TblAccount account = null;
	 try {
                 session=NewHibernateUtil.getSessionFactory().openSession();
		 tx = session.getTransaction();
		 tx.begin();
		 Query query = session.createQuery("from TblAccount where accountId='"+pi_Id+"'");
		 account = (TblAccount)query.uniqueResult();
		 tx.commit();
	 } catch (Exception e) {
		 if (tx != null) {
			 tx.rollback();
		 }
		 e.printStackTrace();
	 } finally {
		 session.close();
	 }
	 return account;
    }
}

 

Step 5: Add Controller Logic by Adding Servlet Controllers

We are now done with our Model and Business Service development. Let’s now create Controller Servlets which will receive the requests from the View (JSP pages) and then route the requests to the Business Service.

Create a new package and name it as Controller. In this package, add a new Java Servlet using New–>Servlet option.

Name the servlet as AddAccountController. This controller will receive the request for Account Addition and then It will route the request to AccountService by calling its addAccount method.

Code of the controller is shown below:

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Controller;
 
import BusinessServices.AccountService;
import Model.TblAccount;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
/**
 *
 * @author Administrator
 */
@WebServlet(name = "AddAccountController", urlPatterns = {"/AddAccountController"})
public class AddAccountController extends HttpServlet {
 
 
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
 
             String pi_AccountTitle=request.getParameter("AccountTitle");
             String pi_AccountType=request.getParameter("AccountType");
             int pi_AccountBalance=Integer.parseInt(request.getParameter("AccountBalance"));
             int pi_accountID=Integer.parseInt(request.getParameter("AccountID"));
 
         TblAccount ac=new TblAccount(pi_accountID, pi_AccountBalance, pi_AccountTitle, pi_AccountType);
         AccountService acs=new AccountService();
         String resultMessage=acs.addAccount(ac);
 
         RequestDispatcher rd =request.getRequestDispatcher("index.jsp?message="+resultMessage); 
          request.setAttribute("searchResult", null);
         rd.forward(request, response);
        } finally {            
            out.close();
        }
    }
 
    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }
 
    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }
 
    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}

 

Now add code logic for our searchController servlet. This servlet will receive requests for searching any account based on account ID value.

Complete servlet code of this searchController servlet is shown below:

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Controller;
 
import BusinessServices.AccountService;
import Model.TblAccount;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
/**
 *
 * @author Administrator
 */
@WebServlet(name = "searchController", urlPatterns = {"/searchController"})
public class searchController extends HttpServlet {
 
    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
          String pi_AccountID=request.getParameter("searchValue");
 
          AccountService acs=new AccountService();
         TblAccount acc_obj= acs.searchAccount(pi_AccountID);
         RequestDispatcher rd =request.getRequestDispatcher("index.jsp"); 
         request.setAttribute("searchResult", acc_obj);
         rd.forward(request, response);
        } finally {            
            out.close();
        }
    }
 
    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }
 
    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }
 
    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}

 

Step 6: Create View in the form of JSP Page

As we are already done with implementation of our Business Service logic, controller logic based on our Model Layer POJOs, now Its time to create the front end of our application.

For UI Layer, I am creating a simple JSP page (index.jsp) which has two forms:

  1. Search Form to submit a search request to the searchController servlet and to display search results in a table.
  2. Add Form to enable user to add a new Account by submitting request to addAccountController servlet.

Complete code of JSP page is shown below:

<%-- 
    Document   : index
    Created on : Nov 17, 2014, 7:47:45 PM
    Author     : Administrator
--%>
 
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ page import="Model.TblAccount" %>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <h1>TutorialsPeida JSP Hibernate Example!</h1>
       <div style="background-color: #FFBBCC; width:40%;"> 
           <br />
           <h2>Account Search Form</h2>
        <form name="searchForm" action="searchController">
            Enter Account ID:<input type="text" name="searchValue" value="" >
            <input type="submit" value="Find Account Details>>" name="searchButton" />
        </form>
        <% TblAccount acc= (TblAccount) request.getAttribute("searchResult"); 
 
        if (acc !=null) 
                {
 
               %>
               <table border="1">
 
                   <tbody>
                       <tr>
                           <td>Account ID</td>
                           <td><% out.println(acc.getAccountId()); %></td>
                       </tr>
                       <tr>
                           <td>Account Title</td>
                           <td><% out.println(acc.getAccountBeneficiary()); %></td>
                       </tr>
                       <tr>
                           <td>Account Balance</td>
                           <td><% out.println(acc.getAccountBalance()); %></td>
                       </tr>
                       <tr>
                           <td>Account Type</td>
                           <td><% out.println(acc.getAccountType()); %></td>
                       </tr>
                   </tbody>
               </table>
 
               <%
                       }
 
 
          %>
           <br /><br /><br />
        </div>
         <br /><br /><br />
        <div style="background-color: #FFBBCC; width:40%;"> 
           <br />
           <h2>Account Creation Form</h2>
        <form name="addForm" action="AddAccountController"><br />
            <table>
            <tr><td>Account ID:</td><td><input type="text" name="AccountID" value="" /></td></tr>
            <tr><td>Account Title:<td><input type="text" name="AccountTitle" value="" /></td></tr>
            <tr><td>Account Balance:<td><input type="text" name="AccountBalance" value="" /></td></tr>
           <tr><td> Account Type: <td>  <input type="text" name="AccountType" value="" /></td></tr>
 
             <tr><td></td><td><input type="submit" value="submitButton" /> </td></tr>
            </table>
          </form>
            <h2>
            <% 
            String rMessage=request.getParameter("message");
            if (rMessage==null)
            rMessage="";
                out.println(rMessage); 
 
            %>
          </h2>
           <br /><br /><br />
          </div>
 
 
 
    </body>
</html>

 

This completes our tutorial developing JSP Hibernate Web Application in Netbeans with Oracle database. Deploy the application in Glass Fish server and run it. You should be able to add new account as well as search for any account information.

 

 

Ajmal Abbasi

Ajmal Hussain Abbasi is a TIBCO Consultant By Profession with more than 6 years experience in TIBCO products. He has extensive practical knowledge of TIBCO Business Works, TIBCO Spotfire, TIBCO BE, EMS and TIBCO ActiveSpaces. He has worked on a number of highly critical integration projects in Telecom sector by using his skills in Tibco Designer, Adapters, TIBCO EMS, RV, Administrator, TIBCO BE, TIBCO ActiveSpaces etc. Ajmal Abbasi is also experienced in developing solutions using Oracle PL/Sql, Linux and Java. You can contact Ajmal Abbasi for Consultancy, Technical Assistance and Technical Discussions.

More Posts - Website - Facebook - LinkedIn

3 thoughts on “JAVA JSP Hibernate Step By Step Tutorial With Oracle Database

Leave a Reply

Your email address will not be published. Required fields are marked *