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" (
  "student_id" BIGINT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
  "first_name" VARCHAR(50) DEFAULT NULL,
  "last_name" VARCHAR(50) DEFAULT NULL,
  "address" VARCHAR(50) DEFAULT NULL,
  PRIMARY KEY ("student_id")
) AUTO_INCREMENT=4 /*!40100 DEFAULT CHARSET=utf8*/;

Step 2: Create Java Object

Student.java

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

Student.hbm.xml

<?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.programcreek.hibernate.Student" table="student">
		<id name="studentId" column="student_id">
			<generator class="increment" />
		</id>
		<property name="firstName" type="string" column="first_name" />
		<property name="lastName" type="string" column="last_name" />
		<property name="address" type="string" column="address" />
	</class>
 
</hibernate-mapping>

Step 4: Create Hibernate configuration file

hibernate.cfg.xml

 <!DOCTYPE hibernate-configuration PUBLIC
          "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
          "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
 
<hibernate-configuration>
 
	<session-factory>
 
		<!-- 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" />
 
	</session-factory>
 
</hibernate-configuration>

Step 5: Create HibernateUtil Helper Class

HibernateUtil.java

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

Test.java

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();
        session.beginTransaction();     
        Student s = new Student("firstname", "lastname", "address");
        session.save(s);
        session.getTransaction().commit();
	}
}

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:
<pre><code> 
String foo = "bar";
</code></pre>

  1. Yeroslav on 2010-11-18

    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 java.net.URLClassLoader $ 1.run (Unknown Source)
    at java.security.AccessController.doPrivileged (Native Method)
    at java.net.URLClassLoader.findClass (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!

  2. admin on 2010-11-19

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

  3. appu on 2012-5-29

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

  4. Genefer on 2014-5-16

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

  5. alvito on 2014-5-19

    sdv

Leave a comment

*