Search This Blog

Saturday, January 29, 2011

Hibernate 3 and Servlet example

Now lets take an example of Hibernate ORM Framework. We will demonstrate the use of hibernate in our servlets. First let us go through the files which hibernate uses. hibernate.cfg.xml is the first file which contains all the information needed to connect to the database (database name, username, password, etc). The next group of xml files contain information regarding the persistent object to be saved. So each object has its own (mapping)file. In our case we will use the "User" object so it will be named user.hbm.xml . The project structure that i use : The Deployable structure : So first we will create our User Model, lets name it User.java . I have created a package in.codeconnect, so the java files will reside in src/in/codeconnect .

package in.codeconnect;

//User Model
public class User {
    private int id;
    private String name;
    private String password;

    //getters and setters
    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

It is a simple class for User, having properties id,name,password with their respective getters and setters. We need a database to store our objects. So we create a database ("application" in my case). With a table having structure : -Users -id (INT NOT NULL DEFAULT 0) -name (VARCHAR) -password (VARCHAR) We will be using mysql database so we need jdbc mysql driver (a jar file), which has to be placed in tomcats lib or in the classpath. Next we create hibernate.cfg.xml file (should be made available in classes directory) :

<?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.driver_class">
            com.mysql.jdbc.Driver
        </property>
        <property name="hibernate.connection.url">
            jdbc:mysql://127.0.0.1:3306/application
        </property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.connection.password"></property>
        <property name="hibernate.connection.pool_size">10</property>
        <property name="show_sql">true</property>
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="hibernate.hbm2ddl.auto">update</property>
        <!-- Mapping files -->
        <mapping resource="user.hbm.xml"/>
    </session-factory>
</hibernate-configuration>
In above file you specify the uri to the mysql server of the format jdbc:mysql://127.0.0.1:3306/application where application is the database name, the username and the password. hibernate.hbm2ddl.auto = update will use the current database state as opposed to create which will recreate the structure resulting in loss of data every time you run ur application. We will now create a mapping file user.hbm.xml which will reside in same directory as above file.

<?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="in.codeconnect.User" table="Users">
        <id name="id" type="int" column="id">
            <generator class="increment"/>
        </id>

        <property name="name">
            <column name="name"/>
        </property>
        <property name="password">
            <column name="password"/>
        </property>
    </class>
</hibernate-mapping>
This file contains the mapping information for our objects (Property to Column). Refer to the id property map and you will see generator class "increment" assigned to it for auto increment even though it is not specified in the database. Now its time to create our servlet HibernateTest to accept our requests. In that we initiate a hibernate session by loading the hibernate config. Next we create our user object and save it using the session. U may get an error related to transaction due to clash with java libs, in that case you need to download jta (jta.jar) library and place it in the classpath/lib. We also retrieve the saved entry from the database and display it.

package in.codeconnect;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import java.io.IOException;
import java.io.PrintWriter;

public class HibernateTest extends javax.servlet.http.HttpServlet {
    protected void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {

    }

    protected void doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        String name = request.getParameter("name");
        String password = request.getParameter("password");
        Session session = null;
        SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
        session = sessionFactory.openSession();
        Transaction transaction = session.beginTransaction();
        
        User user = new User();
        user.setName(name);
        user.setPassword(password);
        session.save(user);
        transaction.commit();
        session.flush();
        
        User userFromDb = (User) session.get(in.codeconnect.User.class,user.getId());
        session.close();
        out.println(userFromDb.getName() + " " + userFromDb.getPassword());
        
    }
}

We now create web.xml tomcat config file in the WEB-INF dir. The content are as follows :

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
    http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
           version="2.5">

    <servlet>
        <servlet-name>HibernateTest</servlet-name>
        <servlet-class>in.codeconnect.HibernateTest</servlet-class>
    </servlet>
    <servlet-mapping>
            <servlet-name>HibernateTest</servlet-name>
            <url-pattern>/HibernateTest</url-pattern>
        </servlet-mapping>

</web-app>
Deploy the application, start the tomcat server and visit the url with params, and the entry should be added to the database. eg : http://localhost:8080/HibernateTest?name=Jhonny&password=Bravo