22 - Hibernate in Web Application

22.1 Overview

We saw how to use Hibernate in standalone java applications in earlier chapter and in this chapter we will discuss how to use hibernate in a web application. We will use eclipse as IDE and Tomcat  as web server for the web application. Refer Chapter3 for the details on installation of Eclipse, Tomcat and Integration of Eclipse with Tomcat.

22.2 Create a Web Application Project

In this section we will discuss how to create a web application using eclipse. We can create it manually as well

  1. To create a new  project go to 

      File -> New -> Project -> Web -> Dynamic Web Project ->Next (refer below)

Once you click Next, new window will open (refer below)

  • Project Name –Give it a name. This will be the name of your web application. In the above figure, web application with name “ManageDatabase” will be created
  • "Target Runtime", choose "Apache Tomcat v7.0"
  • Leave rest all as default values .Click Finish

Once done , a new project with name “ManageDatabase” will be created (refer below figure)

 

Details-

  1. All Java code will be created under src folder
  2. All static contents and jsp will be created under WebContent

To create a War file,  Right Click on Project -> Export -> War file

Clicking on War file, a new window will be opened (refer below). Choose a Destination as the webapps folder of your tomcat installation directory. 

Note- You can select any destination folder and eclipse will create a ManageDatabase.war file at the selected location. However, each server has its own directory from where it deploys the war file.

In case of tomcat “webapps” directory is the deployment directory and for any web application to be deployed on tomcat, it has to be placed in webapps.

22.2.2 Add Hibernate Jar files in build path.

Now is the time to add the jar files of Hibernate that  we downloaded in Chapter 3 (section 3.6) in the java project.

Copy the below jar files and paste in WebContent\WEB-INF\lib folder

  1. antlr-2.7.7.jar
  2. dom4j-1.6.1.jar
  3. hibernate-commons-annotations-4.0.5.Final.jar
  4. hibernate-core-4.3.7.Final.jar
  5. hibernate-jpa-2.1-api-1.0.0.Final.jar
  6. jandex-1.1.0.Final.jar
  7. javassist-3.18.1-GA.jar
  8. jboss-logging-3.1.3.GA.jar
  9. jboss-logging-annotations-1.2.0.Beta1.jar
  10. jboss-transaction-api_1.2_spec-1.0.0.Final.jar
  11. mysql-connector-java-5.1.18-bin.jar  

22.3    Example of managing book table through web application

Let’s  take an example of managing book table through web application. Web application will have a feature of add a new book and display available books.

22.3.1   Design-

a)    Design Book Entity

package com.tutorial.hibernate.entity;

public class Book {    
    private int id;
    private String isbn;
    private String name;
    private String author;
    private String publisher;
    private int price;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getIsbn() {
        return isbn;
    }
    public void setIsbn(String isbn) {
        this.isbn = isbn;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getAuthor() {
        return author;
    }
    public void setAuthor(String author) {
        this.author = author;
    }
    public String getPublisher() {
        return publisher;
    }
    public void setPublisher(String publisher) {
        this.publisher = publisher;
    }
    public int getPrice() {
        return price;
    }
    public void setPrice(int price) {
        this.price = price;
    }    
}

b. Create Book Table- Use the below create script to create book table.

CREATE TABLE 'book' (
  'id' int(11) NOT NULL AUTO_INCREMENT,
  'isbn' varchar(255) DEFAULT NULL,
  'name' varchar(255) DEFAULT NULL,
  'author' varchar(255) DEFAULT NULL,
  'publisher' varchar(255) DEFAULT NULL,
  'price' int(11) DEFAULT NULL,
  PRIMARY KEY ('id');
) 

c. Hibernate.cfg.xml - Create a hibernate.cfg.xml file under src directory of web application.

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

<hibernate-configuration>
        <session-factory>
               <property name="hibernate.connection.url">
                   jdbc:mysql://localhost:3306/tutorial
               </property>
               <property name="hibernate.connection.username">
                   root
               </property>
               <property name="hibernate.connection.password">
                   password
               </property>
               <property name="dialect">org.hibernate.dialect.MySQLDialect</property>

               <property name="show_sql">true</property>
 
               <property name="hibernate.connection.driver_class">
                  com.mysql.jdbc.Driver
               </property>
               <mapping resource="book-mapping.hbm.xml" />
        </session-factory>
</hibernate-configuration>

d. book-mapping.hbm.xml - Create a book-mapping.hbm.xml file under src directory of web application.

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC 
 "-//Hibernate/Hibernate Mapping DTD//EN"
 "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> 
<hibernate-mapping>
   <class name="com.tutorial.hibernate.entity.Book" table="Book">
      <meta attribute="class-description">
         This class contains the employee detail. 
      </meta>
      <id name="id" type="int" column="id">
         <generator class="native"/>
      </id>
      <property name="isbn" column="isbn" type="string"/>
      <property name="name" column="name" type="string"/> 
      <property name="author" column="author" type="string"/>
      <property name="publisher" column="publisher" type="string"/>
      <property name="price" column="price" type="int"/>
       
   </class>
</hibernate-mapping>

e. Create Servlets – We will create two servlets – one to insert the book data and another to retrieve all available book’s data.

GetDataServlet

package com.tutorial.hibernate.servlets;

import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

import com.tutorial.hibernate.entity.Book;
import com.tutorial.hibernate.util.HibernateUtils;

@WebServlet("/GetDataServlet")
public class GetDataServlet extends HttpServlet {
   private static final long serialVersionUID = 1L;

   protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
      SessionFactory factory = HibernateUtils.getSessionFactory();
      Session session = factory.openSession();

      Query query = session.createQuery("from Book");

      List<Book> books = query.list();
      session.flush();
      session.close();
      request.setAttribute("books", books);

      request.getRequestDispatcher("booksDetails.jsp").forward(request, response);        
    }
}

InsertBookServlet

package com.tutorial.hibernate.servlets;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

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

import com.tutorial.hibernate.entity.Book;
import com.tutorial.hibernate.util.HibernateUtils;

@WebServlet("/InsertBookServlet")
public class InsertBookServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
        String isbn = request.getParameter("isbn");
        String name = request.getParameter("name");
        String author = request.getParameter("author");
        String publisher = request.getParameter("publisher");
        String price = request.getParameter("price");

        Book book = new Book();
        book.setAuthor(author);
        book.setIsbn(isbn);
        book.setName(name);
        book.setPrice(Integer.parseInt(price));
        book.setPublisher(publisher);

        SessionFactory factory = HibernateUtils.getSessionFactory();
        Session session = factory.openSession();

        Transaction tx = session.beginTransaction();
        session.save(book);

        session.flush();
        tx.commit();
        session.close();
        response.sendRedirect("GetDataServlet");
    }
}

f. Create JSP files – We will create three JSP files, home page (index.jsp) , insert books screen(insertBook.jsp) and  display books details (bookDetails.jsp).

index.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <title>Manage Books</title>
  </head>
  <body>
     <h3> Manage Books</h3>
     <a href= "GetDataServlet"> Get Books </a>
     <br/>
     <a href= "insertBook.jsp"> Insert Book </a>
  </body>
</html>

insertBook.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <title>Manage Books</title>
  </head>
  <body>
     <%@ page import="java.util.List,com.tutorial.hibernate.entity.*" %>
     <h3> Insert Book </h3>
     <h4> Enter Books Details  </h4>
     <form action="InsertBookServlet" method="POST">
        <table >
           <tr> <td>ISBN </td> 
              <td> <input type="text" name="isbn" /> </td>
           </tr>
           <tr> <td>NAME </td> 
             <td> <input type="text" name="name" /> </td>
           </tr>
           <tr> <td>AUTHOR </td> 
              <td> <input type="text" name="author" /> </td>
           </tr>
           <tr> <td>PUBLISHER </td> 
              <td> <input type="text" name="publisher" /> </td>
           </tr>
           <tr> <td>PRICE </td> 
              <td> <input type="text" name="price" /> </td>
           </tr>
           <tr> <td><input type="Submit" value="Save"/> </td> 
           </tr>
        </table>
     </form>
   </body>
</html>

bookDetails.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
  <head>
     <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
     <title>Manage Books</title>
   </head>
   <body>
      <%@ page import="java.util.List,com.tutorial.hibernate.entity.*" %>
      <h3> Available Books Details </h3>
      <%
         List<Book> books = (List<Book>)request.getAttribute("books");
       %>
      <h4> Total Number of Books are <%= books.size() %> </h4>
      <table border="1">
         <tr>
           <td> ID</td> <td>ISBN </td> <td> NAME </td> <td> AUTHOR </td> <td>PUBLISHER</td> <td> PRICE</td>
         </tr>
          <%
           for(int i=0;i<books.size();i++)
           {
           Book book = books.get(i) ;    
          %>
         <tr> 
           <td><%= book.getId() %></td>
           <td><%= book.getIsbn() %></td>
           <td><%= book.getName() %></td>
           <td><%= book.getAuthor() %></td>
           <td><%= book.getPublisher() %></td>
           <td><%= book.getPrice() %></td>
         </tr>
         <%     
         }
         %>
     </table>
    </body>
</html>

g. Deploy and Run the web application by accessing http://localhost:8080/ManageDatabase

    Below will be home page (index,jsp)

    

Click on InsertBook link and it will display insertBooks.jsp

Add books details and click save

This will save the book details in database and will display the book table data. We can click on Get Books link (available on home screen) also to see the books. 

You can verify that data is stored in table. Refer below table state

22.4 Using JNDI and Data Source

Web applications are multi user application and managed by web or application servers. Instead of opening connection at each request, we can use datasource and instead of configuring the database details, we can use datasource.

To do so, add below lines in context.xml file of tomcat (Available under conf directory of tomcat installation directory)

<Resource name="jdbc/HibernateTutorial" auth="Container" 
     type="javax.sql.DataSource"
     maxActive="100" maxIdle="30" maxWait="10000"
     username="root" password="password" 
     driverClassName="com.mysql.jdbc.Driver"
     url="jdbc:mysql://localhost:3306/tutorial"/>

Once Done, restart the server. Hibernate.cfg.xml file will just need to configure datasource. Refer below hibernate.cfg.xml file for JNDI 

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

<hibernate-configuration>
     <session-factory>
         <property name="hibernate.connection.datasource">java:/comp/env/jdbc/HibernateTutorial</property>        
         <property name="dialect">org.hibernate.dialect.MySQLDialect</property> 
         <property name="show_sql">true</property>        
        <mapping resource="book-mapping.hbm.xml" />        
    </session-factory>
</hibernate-configuration>

Like us on Facebook