Struts 2 Tutorial Series: A simple Hibernate application

Hibernate is a powerful, high performance object/relational persistence and query service. Hibernate lets you develop persistent classes following object-oriented idiom - including association, inheritance, polymorphism, composition, and collections. Hibernate allows you to express queries in its own portable SQL extension (HQL), as well as in native SQL, or with an object-oriented Criteria and Example API.

This applications main function is to add a record to database.

Tools and Libraries we Need

1. JDK 1.5 or above
2. Eclipse IDE
3. Hibernate Core 3.3.2.GA. Download Link.
JAR files required for this application:

4. mysql-connector-java-5.0.8-bin.jar download link.

Step 1: Database Setup.

Create a database "hibernate" on MySQL database. Create a table "student" using the following SQL.

CREATE TABLE /*!32312 IF NOT EXISTS*/ "student" (
  "first_name" VARCHAR(50) DEFAULT NULL,
  "last_name" VARCHAR(50) DEFAULT NULL,
  "address" VARCHAR(50) DEFAULT NULL,
  PRIMARY KEY ("student_id")

Step 2: Create Java Object

package com.programcreek.hibernate;
public class Student {
    private int studentId;
    private String firstName;
    private String lastName;
    private String address;
    public Student() {
    public Student(String firstName, String lastName, String address){
        this.firstName = firstName;
        this.lastName = lastName;
        this.address = address;
    public int getStudentId(){
        return studentId;
    public void setStudentId(int studentId){
        this.studentId = studentId;
    public String getFirstName(){
        return firstName;
    public void setFirstName(String firstName){
        this.firstName = firstName;
    public String getLastName(){
        return lastName;
    public void setLastName(String lastName){
        this.lastName = lastName;
    public String getAddress(){
        return address;
    public void setAddress(String address){
        this.address = address;

Step 3: Create Mapping Files for Java Object


<?xml version="1.0"?>
            <!DOCTYPE hibernate-mapping PUBLIC
                "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
	<class name="com.programcreek.hibernate.Student" table="student">
		<id name="studentId" column="student_id">
			<generator class="increment" />
		<property name="firstName" type="string" column="first_name" />
		<property name="lastName" type="string" column="last_name" />
		<property name="address" type="string" column="address" />

Step 4: Create Hibernate configuration file


 <!DOCTYPE hibernate-configuration PUBLIC
          "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
		<!-- Database connection settings -->
		<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
		<property name="connection.url">jdbc:mysql://localhost/hibernate</property>
		<property name="connection.username">root</property>
		<property name="connection.password">admin</property>
		<!-- SQL dialect -->
		<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
		<!-- Echo all executed SQL to stdout -->
		<property name="show_sql">true</property>
		<property name="current_session_context_class">thread</property>
		<mapping resource="com/programcreek/hibernate/Student.hbm.xml" />

Step 5: Create HibernateUtil Helper Class

package com.programcreek.hibernate.util;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateUtil {
      private static final SessionFactory sessionFactory;
      static {
          try {
              // Create the SessionFactory from hibernate.cfg.xml
              sessionFactory = new Configuration().configure().buildSessionFactory();
          } catch (Throwable ex) {
              // Make sure you log the exception, as it might be swallowed
              System.err.println("Initial SessionFactory creation failed." + ex);
              throw new ExceptionInInitializerError(ex);
      public static SessionFactory getSessionFactory() {
          return sessionFactory;

Step 6: Create a Test Class to Insert a Record

import org.hibernate.Session;
import com.programcreek.hibernate.Student;
import com.programcreek.hibernate.util.HibernateUtil;
public class Test {
	public static void main(String[] args) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        Student s = new Student("firstname", "lastname", "address");;

Finally, the file structure should like this.

After running the test class, the new record will be added to your database. Now we are done with a simplest case.

Category >> Struts 2  
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
String foo = "bar";
  • alvito


  • Genefer

    Am getting “the requested resource not available error’.pls help

  • appu

    hi am appu. this is nice but with explainations required.

  • admin

    I don’t have time to do it recently, but did you check the Lib version. This causes problem sometimes.

  • Yeroslav

    Hello Ryan Wong!!!I just started learning NIBERNATE and I do not start your example. Help me find the error. Here is a screenshot of the error

    java.lang.NoClassDefFoundError: Test
    Caused by: java.lang.ClassNotFoundException: Test
    at $ (Unknown Source)
    at (Native Method)
    at (Unknown Source)
    at java.lang.ClassLoader.loadClass (Unknown Source)
    at sun.misc.Launcher $ AppClassLoader.loadClass (Unknown Source)
    at java.lang.ClassLoader.loadClass (Unknown Source)
    at java.lang.ClassLoader.loadClassInternal (Unknown Source)
    Exception in thread “main”

    If you can send me to this beautiful post your project, would be very grateful! ”

    Thank you!