JAVA JSP Hibernate Step By Step Tutorial With Oracle Database

In this Java JSP Hibernate 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"?-->
 
 
 
    org.hibernate.dialect.OracleDialect
    oracle.jdbc.OracleDriver
    jdbc:oracle:thin:@localhost:1521:XE
    SYSTEM
    admin

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"?-->

 

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"?-->
 
<!-- Generated Nov 17, 2014 9:32:00 PM by Hibernate Tools 3.2.1.GA -->

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();
        }
    }
 
    // 
    /**
     * 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"; }// }

 

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(); } } // /** * 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"; }// }

 

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:

&lt;%-- Document : index Created on : Nov 17, 2014, 7:47:45 PM Author : Administrator --%&gt;
 
&lt;%@page contentType="text/html" pageEncoding="UTF-8"%&gt;
&lt;%@ page import="Model.TblAccount" %&gt;

TutorialsPeida JSP Hibernate Example!

 

Account Search Form

 

Enter Account ID:

<% TblAccount acc= (TblAccount) request.getAttribute(“searchResult”); if (acc !=null) { %>

Account ID <% out.println(acc.getAccountId()); %>
Account Title <% out.println(acc.getAccountBeneficiary()); %>
Account Balance <% out.println(acc.getAccountBalance()); %>
Account Type <% out.println(acc.getAccountType()); %>

<% } %>

 

 

 

Account Creation Form

 

 

Account ID:
Account Title:
Account Balance:
Account Type:

 

 

<% String rMessage=request.getParameter(“message”); if (rMessage==null) rMessage=””; out.println(rMessage); %>

 

 

 

 

 

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 Integration Consultant By Profession with 13+ years experience in Integration domain mainly with TIBCO products. He has extensive practical knowledge of TIBCO Business Works, TIBCO Cloud, TIBCO Flogo, TIBCO Mashery, TIBCO Spotfire, EMS and TIBCO ActiveSpaces. He has worked on a number of highly critical integration projects in various sectors by using his skills in TIBCO Flogo, TIBCO API Management (Mashery), TCI, Tibco Designer, TIBCO Business Studio, Adapters, TIBCO EMS, RV, Administrator, TIBCO BE, TIBCO ActiveSpaces etc. Ajmal Abbasi has experience with MuleSoft ESB as well. Ajmal Abbasi is also experienced in the area of API Management particularly with WSO2 API management platforms. Ajmal Abbasi is also experienced in developing solutions using Core Java and J2EE Technologies. You can contact Ajmal Abbasi for Consultancy, Technical Assistance and Technical Discussions.

More Posts - Website - Facebook - LinkedIn - YouTube

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

  1. Anita

    i didn’t find save() method in Account Service. don’t save data in database

    Reply
  2. HP Support

    Thanks for writing a valuable blog which resolve my issues. And I request you to write a blog in which edit and form print or view error are resolving.

    Reply
  3. shukr sharma

    sir widout primary key rev engg wiz file not selected

    i use ntbean 8.2
    oracle 10g

    Reply

Leave a Reply to Nishi Narmada Cancel reply

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