Monday, May 18, 2009

Basic Hibernate Annotations example

As part of my POC, today I developed a simple hibernate annotations based example. To run this example, you need JDK 5.0 or higher and hibernate 3.2.0.GA or above. I am using JDK 1.6, MySql 5.1, Tomcat 6.0.18 and Hibernate 3.3.1.GA.

Create hibernate.cfg.xml file. This file should be available in the classpath at runtime. I developed this example as part of a web application and I am using a datasource defined in my container. See my earlier post on How to configure a datasource in Tomcat

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
<property name="connection.datasource">java:comp/env/jdbc/travel</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="current_session_context_class">thread</property>
<property name="show_sql">true</property>
<mapping class=""/>

This example needs following table in your database.

CREATE TABLE airline (
code char(2) PRIMARY KEY,
name varchar(50) NOT NULL,
created timestamp DEFAULT NOW() NOT NULL

Create HibernateUtil class which provides Hibernate session to interact with database. new AnnotationConfiguration().configure() looks for hibernate.cfg.xml in the classpath, so make sure to deploy the file in WEB-INF/classes directory.


import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;

public class HibernateUtil {
private static final SessionFactory sessionFactory;

static {
try {
sessionFactory = new AnnotationConfiguration().configure()
} catch (Throwable ex) {
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);

public static SessionFactory getSessionFactory() {
return sessionFactory;

Airline class maps with the airline table we created above. Notice the annotations used to define the mapping.


import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Table(name = "airline")
public class Airline implements Serializable {
private static final long serialVersionUID = 6864693643526282786L;
@Column(name = "code")
private String code;
@Column(name = "name")
private String name;
@Column(name = "created")
private Date createdTime;

public String getCode() {
return code;

public void setCode(String code) {
this.code = code;

public String getName() {
return name;

public void setName(String name) { = name;

public Date getCreatedTime() {
return createdTime;

Simple servlet to test the application. I used the hibernate code directly in my servlet for simplicity. You should define one DAO layer to encapsulate the hibernate code. To test acccess your servelt use url like http://host:port/travel/AirlineServlet?code=LH&name=Lufthansa


import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class AirlineServlet extends HttpServlet {
private static final long serialVersionUID = 2409603422056073641L;

protected void service(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
SessionFactory session = HibernateUtil.getSessionFactory();
Session sess = session.getCurrentSession();
Transaction tx = sess.beginTransaction();
// Get the airline code and name
String airlineCode = request.getParameter("code");
String airlineName = request.getParameter("name");
// Create Airline object
Airline airline = new Airline();
// Save the record in database;

1 comment: