Hibernate Framework Tutorial in JAVA using Annotation

 

In my last tutorial you have seen how to configure and use Hibernate Framework in JAVA using configuration file. Here I have explained how to configure and use Hibernate Framework using annotation. Entity mapping file (entity_name.hbm.xml) is no more required if you are using annotations. All the mapping details are given in the entity class itself.

Pros and Cons of Hibernate Annotations:
Pros:

  1. Annotations are less verbose.
  2. As the annotations reside in the code itself, errors can be identified at the time of compilation.
  3. Hibernate Framework supports JPA persistence annotations. So later if in case you do not want to use Hibernate Framework in future, then other ORM frameworks which support JAP persistence annotations can be used.

Cons:

  1. Changing the mapping metadata information required recompilation of the java file.
  2. As the annotation classes are imported in the java file, it creates dependency with the API.

Folder Structure:
Folder Structure of Hibernate Framework in JAVA using Annotation

Files:
1.Hibernate.cfg.xml:
The hibernate configuration file remains the same but instead of <mapping resource=”…”>
you will use <mapping class=”…”> and provide the fully qualified name of the Entity class.

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
 "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
 "http://www.hibernate.org/dtd/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:3306/Login</property>
        <property name="connection.username">root</property>
        <property name="connection.password">admin</property>

        <!-- JDBC connection pool (use the built-in) -->
        <property name="connection.pool_size">1</property>

        <!-- SQL dialect -->
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>

        <!-- Enable Hibernate's automatic session context management -->
        <property name="current_session_context_class">thread</property>

        <!-- Disable the second-level cache -->
        <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>

        <!-- Echo all executed SQL to stdout -->
        <property name="show_sql">true</property>

        <!-- Mapping files -->
        <!-- <mapping resource="user.hbm.xml" /> -->
		<mapping class="com.hibernate.domain.User" />
    </session-factory>
</hibernate-configuration>

2.User.java:
This is the entity class corresponding to the user table in database. In this class you use annotations to provide the mapping information.

Here’s the description of the used annotations:

@Entity – This annotation is used to tell Hibernate class that the java class is an Entity.
@Table – This annotation is use to map the database table.
@Id – It tells the property is a primary key.
@GeneratedValue – This annotation is used to specify the generation strategies for the value of primary key.
@Column – It maps the table columns with the properties in the java class.

package com.hibernate.domain;

import java.io.Serializable;

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

@Entity
@Table ( name = "user")
public class User implements Serializable {
	private static final long serialVersionUID = 1428480656398059725L;
	
	private int userId;
	private String userName;
	private String password;
	private String eMail;
	private String name;
	
	@Id
	@GeneratedValue (strategy=GenerationType.AUTO)
	@Column (name="user_id")
	public int getUserId() {
		return userId;
	}
	public void setUserId(int userId) {
		this.userId = userId;
	}
	
	@Column (name="user_name")
	public String getUserName() {
		return userName;
	}
	public void setUserName(String userName) {
		this.userName = userName;
	}
	
	@Column (name="password")
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	
	@Column (name="email")
	public String geteMail() {
		return eMail;
	}
	public void seteMail(String eMail) {
		this.eMail = eMail;
	}
	
	@Column (name="name")
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
}

3.HibernateUtil.java:
This is the java file which is used to get the Hibernate session object. When you use annotations “SessionFactory” object should be created using “AnnotationConfiguration” class.

package com.hibernate.util;

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

public class HibernateUtil {
	private static SessionFactory sessionFactory = null;
	private static Session session = null;
	static{
		try{
			sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
		} catch (Exception e){
			System.out.println("Unable to create session factory");
			e.printStackTrace();
		}
	}
	
	public static Session getSession(){
		if(session == null){
			try{
				session = sessionFactory.openSession();
			} catch (Exception e){
				System.out.println("Unable to create session");
				e.printStackTrace();
			}
		}
		return session;
	}
}

4.Test.java:
This is the class which contains “main()” where you get the Hibernate session using “HibernateUtil” and persist a user record to the database.

package com.hibernate;

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

import com.hibernate.domain.User;
import com.hibernate.util.HibernateUtil;

public class Test {
	Session session = null;
	Transaction txn = null;
	
	public void saveUser(User user){
		try{
			session = HibernateUtil.getSession();
			txn = session.beginTransaction();
			session.save(user);
			txn.commit();
		} catch (Exception e){
			System.out.println("Unable to save user details to the DB");
			e.printStackTrace();
			txn.rollback();
		} finally {
			if(session != null){
				if(session.isDirty()){
					session.close();
				}
			}
		}
	}
	
	public static void main(String[] args) {
		User user = new User();
		user.setUserName("james");
		user.setPassword("password01");
		user.setName("James Gosling");
		user.seteMail("jgosling@yahoo.com");
		
		Test test = new Test();
		test.saveUser(user);
	}
}

Leave a comment

SUBSCRIBE TO NEWSLETTER

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Categories