How to Use Hibernate Framework in JAVA

 

In this tutorial we are going to learn about how to configure and use Hibernate Framework in JAVA applications.

What is Hibernate?

Hibernate is a lightweight ORM (Object Relational Mapping) tool. Hibernate internally uses JDBC to perform all the database operations. It has various advantages, which are listed below.

  1. It is light weight.
  2. It removes the boiler plate code.
  3. We don’t need to write the complex query by our own. Hibernate generates the query.
  4. It provides flexible Transaction management techniques.
  5. It works across all databases.
  6. It provides caching mechanism which gives better performance.

How to configure Hibernate to our application?

To use Hibernate in our application we need to add the Hibernate JARs to our application’s class path. Once it is added in the class path all the functionalities are available to our application.

There are two ways we can use hibernate in our application.

  1. By using Configuration files
  2. By using annotations

In this post I will show you how to use Hibernate Framework in JAVA using the configuration file.
Resources required:

  1. Hibernate JARs
  2. MySql Connector jar

Folder Structure:
Folder Structure of Hibernate Framework in JAVA

Files:
1.hibernate.cfg.xml
This is the configuration file that contains the information about the database and the mapping file. Database details like Dialect, connection URL, username, password etc are configured here in this file.

<?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.hibernateproject.domain.User" /> -->
    </session-factory>
</hibernate-configuration>

2.User.hbm.xml
This is the xml file where we provide mapping details. Conventionally its name should be class_name.hbm.xml (here our entity class name is user, hence the name user.hbm.xml).

<?xml version='1.0' encoding='UTF-8'?>  
<!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.hibernateproject.domain.User" table="USER">
 		<id name="username" column="user_name"></id>
 		<property name="password"></property>
 		<property name="name"></property>
 		<property name="email"></property>
 	</class>
 </hibernate-mapping>

3.User.java – Java class (Persistent class)
It is a POJO (Plain Old Java Object). This class represents the USER table in the database as a JAVA object. Each attributes corresponds to a specific column name in the table. The entries are given in mapping file (user.hbm.xml).

package com.hibernateproject.domain;
import java.io.Serializable;

public class User implements Serializable{
	private String username;
	private String password;
	private String name;
	private String email;
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getEmail() {
		return email;
	}
	public void setEmail(String email) {
		this.email = email;
	}
	
}

4.HibernateUtil.java
This is the java class where we create SessionFactory object and Session object as well.

package com.hibernateproject.util;

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

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

5.Test.java
This is the java class where we use hibernate session to save a record in the USER table.

package com.hibernateproject;

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

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

public class Test {
	public void saveUser(User user){
		Session session = null;
		Transaction txn = null;
		try{
			session = HibernateUtil.getSession();
			txn= session.beginTransaction();
			session.save(user);
			txn.commit();
		} catch (Exception e){
			e.printStackTrace();
			txn.rollback();
			System.out.println("Unable to save user details to the database;");
		} finally {
			if(session != null){
				if(session.isOpen()){
					session.close();
				}
			}
		}
	}
	
	public static void main(String[] args) {
		Test test = new Test();
		User user = new User();
		user.setUsername("john");
		user.setPassword("password01");
		user.setEmail("abc@gmail.com");
		user.setName("John Lennon");
		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