Srikanth Technologies

Using Hibernate From Web Applications

In this blog, I write about how to access database using Hibernate from a web application. We also use annotations instead of XML mapping file. I am using NetBeans IDE. However you can use any other IDE with a few changes related to steps but not code. NetBeans IDE 6.5 comes with Hibernate support. But in the following steps, we will see how to deal with configuration files and libraries assuming we are not using NetBeans IDE 6.5.

Getting Hibernate Ready

Follow the steps given below to install Hibernate.
  1. Go to www.hibernate.org website, download latest version of hibernate.
  2. You get a single .zip file.
  3. Unzip .zip file into a folder like c:\hibernate.
That’s all you have to do to get hibernate ready.

Create Library In NetBeans IDE

In order to use hibernate in multiple projects in NetBeans, it is better you create a library in NetBeans.
  1. Go to Tools->Libraries.
  2. Click on New Library button at the bottom of the window.
  3. Enter library name as hibernate.
  4. Click on Add Jar/Folder button and go to c:\hibernate folder and select hibernate3.jar first.
  5. Use the Add Jar/Folder button again and go to c:\hibernate\lib folder and select all .jar files in that folder.
Now your hibernate library is ready to be used.

Creating a new web project

Create a new web application using NetBeans as follows.
  1. Select File->New Project. Select web in categories. Select Web Application in projects list.
  2. Enter project name as hibernateweb and select folder where you want to create this project.
  3. Select Apache Tomcat as the server and select no frameworks in the last step.
  4. You have a new web application created by NetBeans.
  5. Go to Libraries node in the Project window and right click. Select Add Library option and select hibernate as the library to be added to project.
  6. As we use Oracle from this project, add Oracle’s JDBC jar file - ojdbc14.jar also to your project. You can use Add JAR/Folder option and add ojdbc14.jar library.

Creating Hibernate Configuration File and Entity

This project makes use of a single entity called Subscriber, which is placed in entities package. We use @Entity annotation to make Subscriber class an entity. Hibernate uses the same annotations that JPA uses.

package entities;

import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.Id;

@Entity
public class Subscriber implements Serializable {
    @Id
    private String uname;
    private String pwd;
    
    public Subscriber() {
    }
    public String getUname() {
        return uname;
    }
    public void setUname(String uname) {
        this.uname = uname;
    }

    public String getPwd() {
        return pwd;
    }

    public void setPwd(String pwd) {
        this.pwd = pwd;
    }
}

Create hibernate.cfg.xml file as shown below. It must be in default package. Go to Source Packages and then to <default package> and place hibernate.cfg.xml.

<?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>
        <!-- Database connection settings -->
        <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
        <property name="connection.url">jdbc:oracle:thin:@localhost:1521:XE</property>
        <property name="connection.username">hib</property>
        <property name="connection.password">hib</property> 
        <!-- JDBC connection pool (use the built-in) -->
        <property name="connection.pool_size">1</property>
        <!-- SQL dialect -->
        <property name="dialect">org.hibernate.dialect.Oracle10gDialect</property>
        <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
        <!--create the database schema on startup if required -->
        <property name="hbm2ddl.auto">update</property>
        <mapping class="entities.Subscriber"/>
  </session-factory>
</hibernate-configuration>

The above configuration file provides details regarding database connection, which is oracle 10g in this case, and sql dialect and entity class - entities.Subscriber. Hibernate creates the required tables in the database as we used update for hbm2ddl property. 

Creating web pages and servlets

Now let us create register.html page to take details regarding the user and RegisterServlet, which uses Hibernate session to persist Subscriber object to database. Here is register.html. Place it under Web Pages node.

<%@page contentType="text/html"%>
<%@page pageEncoding="UTF-8"%>

<!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=UTF-8">
        <title>Registration</title>
    </head>
    <body>
    <h1>Registration</h1>
    <form action="register" method="post">
        <table cellpadding="3pt">
            <tr>
                <td>Username : </td>
                <td><input type="text" name="uname" size="20"/> </td>
            </tr>
            <tr>
                <td>Password : </td>
                <td><input type="password" name="pwd" size="20"/> </td>
            </tr>
            
            <tr>
                <td>Confirm Password : </td>
                <td><input type="password" name="pwd2" size="20"/> </td>
            </tr>
        </table>
        <p/>
         <input type="submit" value="Register"/>
      </form>
    </body>
</html>

Create RegisterServlet.java with register as URL pattern as given below.

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import entities.*;
import org.hibernate.cfg.AnnotationConfiguration;

public class RegisterServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        String uname = request.getParameter("uname");
        String pwd = request.getParameter("pwd");
        try {
         SessionFactory sf =  new AnnotationConfiguration().configure().buildSessionFactory(); 
         Session s = sf.openSession();
       
         Subscriber sub = new Subscriber();
         sub.setUname(uname);
         sub.setPwd(pwd);
         s.beginTransaction();
         s.save(sub);
         s.getTransaction().commit();
         s.close();
         sf.close();
         out.println( "<h3>[" + uname + "] has been registered successfully!</h3>");
        }
        catch(Exception ex) {
            out.println("<h3>[" + uname + "] could NOT be registered!</h3>");
            System.out.println(ex.getMessage());
        }
    }
}

Build and deploy the application using context menu option like Build and Deploy (or Undeploy and Deploy). Run register.html using the following URL (or select register.html and choose Run File option from context menu).

http://localhost:8084/hibernateweb/register.hml

Enter details in the text boxes and click on Register button. You must see a message from Servlet about the status of registration. If registration is successful, you also see a row in Subscriber table in the database.

That’s all you have to do to use Hibernate with annotations in web application.

Using Mapping File Instead of Annotations

If you want to use mapping file instead of XML, you have to make the following changes.

Create mapping file – Subscriber.hbm.xml in entities package as follows.

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <class name="entities.Subscriber" table="SUBSCRIBER">
        <id name="uname" column="uname">
            <generator class="assigned"/>
        </id>
        <property name="pwd"/>
    </class>
</hibernate-mapping>

Change hibernate.cfg.xml file as follows.
<?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>
        <!-- Database connection settings -->
        <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
        <property name="connection.url">jdbc:oracle:thin:@localhost:1521:XE</property>
        <property name="connection.username">hib</property>
        <property name="connection.password">hib</property> 
        <!-- JDBC connection pool (use the built-in) -->
        <property name="connection.pool_size">1</property>
        <!-- SQL dialect -->
        <property name="dialect">org.hibernate.dialect.Oracle10gDialect</property>
        <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
        <!-- Drop and re-create the database schema on startup -->
        <property name="hbm2ddl.auto">update</property>
        <mapping resource="entities/Subscriber.hbm.xml"/>
     </session-factory>
  </hibernate-configuration>

Change code to get SessionFactory in RegisterServlet.java as follows.

   

try {
         SessionFactory sf =  new Configuration().configure().buildSessionFactory(); 
         Session s = sf.openSession();
          ...
}

The result of the above changes must be same as before. Instead of using annotations we are using mapping file to map Subscriber class to Subscriber table. There is no need to change class Subscriber, you can leave annotation as they are as anyway they are not taken by Hibernate. Hibernate uses annotations only when AnnotationConfiguration() is used.