Hibernate Hello World Application

This article shows how to develop a new Hibernate Hello World project. A sample application is below :

Using Technologies :

JDK 1.6.0_21
Maven 3.0.2
Hibernate 3.6.7
MySQL Java Connector 5.1.17
MySQL 5.5.8

STEP 1 : CREATE USER TABLE

A new USER Table is created by executing below script:

CREATE TABLE USER (
   id int(11) NOT NULL,
   name varchar(45) NOT NULL,
   surname varchar(45) NOT NULL,
   PRIMARY KEY (`id`)
);


STEP 2 : CREATE MAVEN PROJECT

A maven project is created as below. (It can be created by using Maven or IDE Plug-in).

STEP 3 : LIBRARIES

Hibernate, MySQL Java connector and the dependencies libraries are added to Maven’ s pom.xml. These libraries will be downloaded by Maven Central Repository.

<dependency>
   <groupId>org.hibernate</groupId>
   <artifactId>hibernate-core</artifactId>
   <version>3.6.7.Final</version>
</dependency>

<dependency>
   <groupId>mysql</groupId>
   <artifactId>mysql-connector-java</artifactId>
   <version>5.1.17</version>
</dependency>

<dependency>
   <groupId>javassist</groupId>
   <artifactId>javassist</artifactId>
   <version>3.12.1.GA</version>
</dependency>

STEP 4 : HIBERNATE CONFIG PARAMETERS

Hibernate Config parameters are set as below :

<?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://localhost:3306/Test</property>
      <property name="hibernate.connection.username">root</property>
      <property name="hibernate.connection.password">root</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="hbm/user.hbm.xml"/>
   </session-factory>
</hibernate-configuration>

STEP 5 : CREATE USER TABLE

User Table Configuration are set as below.

<?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="com.otv.hbm.User" table="USER">
   <id name="id" type="int" column="ID" >
   <generator class="increment"/>
  </id>

  <property name="name">
    <column name="NAME" />
  </property>
  <property name="surname">
    <column name="SURNAME"/>
  </property>
 </class>
</hibernate-mapping>

STEP 6 : HibernateUtil CLASS

Singleton HibernateUtil class is created to build a Hibernate SessionFactory Object.

package com.otv.util;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

/**
 * @author onlinetechvision.com
 * @since 30 Sept 2011
 * @version 1.0.0
 *
 */
public class HibernateUtil {

	private static SessionFactory sessionFactory = null;

	public static SessionFactory getSessionFactory() {
		if(sessionFactory == null) {
			sessionFactory = new Configuration().configure().buildSessionFactory();
		}
		return sessionFactory;
	}

	public static void setSessionFactory(SessionFactory sessionFactory) {
		HibernateUtil.sessionFactory = sessionFactory;
	}
}

STEP 7 : HibernateUtil CLASS 

A new User Pojo Class is created as below. This User class is mapped to USER Table.

package com.otv.hbm;

/**
 * @author onlinetechvision.com
 * @since 30 Sept 2011
 * @version 1.0.0
 *
 */
public class User {

	private int id;
	private String name;
	private String surname;

	public User() {

	}

	public User(String name, String surname) {
		this.name = name;
		this.surname = surname;
	}

	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 getSurname() {
		return surname;
	}

	public void setSurname(String surname) {
		this.surname = surname;
	}	

	@Override
	public String toString() {
		StringBuffer strBuff = new StringBuffer();
		strBuff.append(", name : ").append(name);
		strBuff.append(", surname : ").append(surname);
		return strBuff.toString();
	}
}

STEP 8 : FULL EXAMPLE 

package com.otv;

import org.apache.log4j.Logger;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import com.otv.hbm.User;
import com.otv.util.HibernateUtil;

/**
 * @author onlinetechvision.com
 * @since 30 Sept 2011
 * @version 1.0.0
 *
 */
public class Application {

	private static Logger log = Logger.getLogger(Application.class);

	private SessionFactory sessionFactory = HibernateUtil.getSessionFactory();

	public static void main(String[] args) {
		Application app = new Application();

		//A new User is created...
		User user  = new User("Nathalie", "West");

		//user record is inserted and id information returns...
		Integer userId = app.saveUser(user);

		//user record is updated...
		app.updateUser(userId, "Michael", "East");

		//user record is deleted...
		app.deleteUser(userId);

		//SessionFactory is closed...
		sessionFactory.close();
	}

	private Integer saveUser(User user) {
		Session session = null;
		Transaction tx = null;
		Integer userId = null;
		try {
			//session is gotten...
			session = sessionFactory.openSession();

			//transaction is started...
			tx = session.beginTransaction();

			//user record is inserted...
			userId = (Integer) session.save(user);

			//transaction is committed...
			tx.commit();
			log.debug("New Record : " + user + ", wasCommitted : " + tx.wasCommitted());
		} catch (Exception e) {
			if (tx != null) {
				//transaction will be rollbacked when an exception is thrown...
				tx.rollback();
				log.error("New Record : " + user + " can not be inserted!!!");
				e.printStackTrace();
			}
		} finally {
			//session is closed
			session.close();
		}
		return userId;
	}

	private void updateUser(Integer userId, String name, String surname) {
		Session session = null;
		Transaction tx = null;
		try {
			//session is gotten...
			session = sessionFactory.openSession();

			//transaction is started...
			tx = session.beginTransaction();

			//User record which will be updated is gotten from session and new name and surname values are set...
			User user = (User) session.get(User.class, userId);
			user.setName(name);
			user.setSurname(surname);

			//user record is updated...
			session.update(user);

			//transaction is committed...
			tx.commit();
			log.debug("Updated Record : " + user + ", wasCommitted : " + tx.wasCommitted());
		} catch (Exception e) {
			if (tx != null) {
				//transaction will be rollbacked when an exception is thrown...
				tx.rollback();
				e.printStackTrace();
			}
		} finally {
			//session is closed
			session.close();
		}
	}

	private void deleteUser(Integer userId) {
		Session session = null;
		Transaction tx = null;
		try {
			//session is gotten...
			session = sessionFactory.openSession();

			//transaction is started...
			tx = session.beginTransaction();

			//User record which will be deleted is gotten from session...
			User user = (User) session.get(User.class, userId);

			//user record is deleted...
			session.delete(user);

			//transaction is committed...
			tx.commit();
			log.debug("Deleted Record : " + user + ", wasCommitted : " + tx.wasCommitted());
		} catch (Exception e) {
			if (tx != null) {
				//transaction will be rollbacked when an exception is thrown...
				tx.rollback();
				e.printStackTrace();
			}
		} finally {
			//session is closed
			session.close();
		}
	}
}

STEP 9 : OUTPUT 

When Application Class is run, the output will be seen as below :

Hibernate: select max(ID) from USER
Hibernate: insert into USER (NAME, SURNAME, ID) values (?, ?, ?)
30.09.2011 17:58:55 DEBUG (Application.java:54) - New Record : , name : Nathalie, surname : West, wasCommitted : true
Hibernate: select user0_.ID as ID0_0_, user0_.NAME as NAME0_0_, user0_.SURNAME as SURNAME0_0_ from USER user0_ where user0_.ID=?
Hibernate: update USER set NAME=?, SURNAME=? where ID=?
30.09.2011 17:58:55 DEBUG (Application.java:89) - Updated Record : , name : Michael, surname : East, wasCommitted : true
Hibernate: select user0_.ID as ID0_0_, user0_.NAME as NAME0_0_, user0_.SURNAME as SURNAME0_0_ from USER user0_ where user0_.ID=?
Hibernate: delete from USER where ID=?
30.09.2011 17:58:55 DEBUG (Application.java:120) - Deleted Record : , name : Michael, surname : East, wasCommitted : true

STEP 10 : DOWNLOAD 
OTV_Hibernate

  • Facebook
  • Twitter
  • Reddit
  • LinkedIn
  • DZone
  • Add to favorites
  • Email
  • RSS
  • Delicious
  • Live