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 . 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) { = id;
public String getName() {
return name;

public void setName(String 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 :

-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) :


In above file you specify the uri to the mysql server of the format jdbc:mysql:// where application is the database name, the username and the password. = 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.

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;

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 {
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 userFromDb = (User) session.get(in.codeconnect.User.class,user.getId());
out.println(userFromDb.getName() + " " + userFromDb.getPassword());


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

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

1 comment:

  1. Good tutorial but is there a way that you can reuse the session instead of calling sessionFactory.openSession() in every servlet? Or is that the recommended way to do it?