Hibernate 4 Annotations Tutorial

In this video tutorial you will learn how to use Hibernate 4 Annotations for writing simple programs.

Hibernate 4 Annotations Tutorial

Video Tutorial: Hibernate 4 Annotations Tutorial

In this video tutorial I will explain you the steps needed to create example program using Annotations in Hibernate 4. Hibernate 4 is popular ORM framework and comes with many new features. This video tutorial explains you the steps and the code for creating such applications. We have used the Eclipse IDE.

What is Hibernate Annotations?

The Java 5 introduced a powerful way to provide the meta-data information in the program in the form of Annotations. Using this feature of Java 5 Oracle created the persistence API in which annotations can be used for providing the meta-data to the POJO class. These API's are packaged in the javax.persistence package. The important annotations are @Entity, @Table, @Id, @GeneratedValue, @Column etc.. With the help of annotations user's can easily develop the meta-data information of their entity. Moreover the Entity declaration and the meta-data resides in the same (java) file which makes the maintenance of the application much easier. Here we will use all these annotations in the example program.

Prerequisite

  • Eclipse must and installed on your computer
  • You should have MySQL database installed on your computer
  • You should have good Java programming knowledge
  • You should already know how to create database and table in MySQL database

Here is the video of Hibernate 4 Annotation Tutorial:

Here is the brief description of the Hibernate 4 Annotation Tutorial video.

Create a new project in Eclipse IDE as shown below:

Add the required library files into the project. You can get all these files from the lib directory of latest Hibernate 4 download. Following screen shot displays all the required jar files:

Here are the names of Hibernate 4 required jar files:

  • antlr-2.7.7.jar
  • dom4j-1.6.1.jar
  • hibernate-commons-annotations-4.0.2.Final.jar
  • hibernate-core-4.2.6.Final.jar
  • hibernate-jpa-2.0-api-1.0.1.Final.jar
  • javassist-3.15.0-GA.jar
  • jboss-logging-3.1.0.GA.jar
  • jboss-transaction-api_1.1_spec-1.0.1.Final.jar
  • mysql-connector-java-5.1.25-bin.jar

Following screen shot shows the code of hibernate.cfg.xml file:

Here is the code of hibernate.cfg.xml file:

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://www.hibernate.org/dtd/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/hibernatetutorials</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.current_session_context_class">thread</property>

<mapping class="net.roseindia.Person" />
</session-factory>
</hibernate-configuration>

Following screen shot shown the code of entity class:

Here is the code of Entity class (Person.java):

package net.roseindia;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table (name= "person")
public class Person
{
	@Id
	@GeneratedValue
	@Column(name = "Id")
	private int id;
	
	@Column(name = "name")
	private String name;
	
	public Person()
	{
		
	}
	public Person(int id, String name) {
		super();
		this.id = id;
		this.name = name;
	}
	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;
	}
}

Here is the code of AppFactory.java which configures the session factory for the application:


package net.roseindia;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

public class AppFactory {
	private static ServiceRegistry serviceRegistry;

	private static final SessionFactory sessionFactory;
	static {
		try {
			Configuration configuration = new Configuration();
			configuration.configure();
			serviceRegistry = new ServiceRegistryBuilder().applySettings(
					configuration.getProperties()).buildServiceRegistry();
			sessionFactory = configuration.buildSessionFactory(serviceRegistry);
		} catch (Throwable ex) {
			System.err.println("Failed to create sessionFactory object." + ex);
			throw new ExceptionInInitializerError(ex);
		}
	}

	public static SessionFactory getSessionFactory() {
		return sessionFactory;
	}
}

Here the example code for testing the application:

package net.roseindia;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

public class RunExample
{
	private static SessionFactory sessionFactory = null;
	public static void main(String[] args)
	{		
		Session session = null;
		try 
		 {
			try
			{
				sessionFactory = AppFactory.getSessionFactory();
				session = sessionFactory.openSession();
				

				
				System.out.println("Inserting Record");
				Transaction tx = session.beginTransaction();
			
				Person person = new Person();
				person.setName("Hibernate example");				
				
				session.save(person);
				tx.commit();
				
				System.out.println("Done");
			}
			catch (Exception e)
			{
				System.out.println(e.getMessage());
			}
			}
			finally
			{
				session.close();
			}
		}
	}

Following screen shot shows the code from RunExample.java file:

If you run the application it will add the data into database table.

In this video tutorial you have learned how to create Hibernate 4 Annotation example program. Video tutorial explained you the steps needed to create Hibernate example.

Download the source code of Hibernate 4 Annotation example discussed here.