Hibernate Example

This tutorial illustrate an example of hibernate

Hibernate Example

Hibernate Example

This tutorial illustrate an example of hibernate.

Hibernate provide a way of mapping of applications class to the database table.
It maps each class properties to the corresponding columns of table. After mapping to the table, all operations are performed by using the object of class in which table is mapped.
Hibernate is an ORM based programming technology provides mapping library.
Here is a simple example of mysql database connectivity using hibernate. Here we are describing this example step by step.

Step 1. Configuring Hibernate-

hibernate-cfg.xml is configuration file saved in the same folder where the source code of class file is saved. It creates the connection pool and set-up required environment.


<?xml version='1.0' encoding='utf-8'?>
<!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:3306/hibernate</property>
<property name="connection.username">root</property>
<property name="connection.password">root</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>

<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">none</property>
<mapping class="net.roseindia.table.Employee" />
</session-factory>

</hibernate-configuration>

In <hibernate-configuration> you configure your database connectivity, set sql dialect ,create database schema etc.
Here hibernate is your database name which contain tables. ?net.roseindia.table.Employee" is your class in which you are mapping your table.


Step 2. Persistent class:

Now create Persistent class ?Hibernate uses the Plain Old Java Object (POJO) classes to map to the database table.

Here is the code of Employee.java-

package net.roseindia.table;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

@javax.persistence.Entity
@Table(name = "employee") //database table name employee
public class Employee implements Serializable {

@Id
@GeneratedValue
private int empId;

@Column(name = "emp_name", nullable = false)
private String empName;

@Column(name = "emp_salary", nullable = false)
private int salary;

@Column(name = "designation", nullable = false)
private String designation;

@Column(name = "address", nullable = false)
private String address;

public int getEmpId() {
return empId;
}

public void setEmpId(int empId) {
this.empId = empId;
}

public String getEmpName() {
return empName;
}

public void setEmpName(String empName) {
this.empName = empName;
}

public int getSalary() {
return salary;
}




public void setSalary(int salary) {
this.salary = salary;
}

public String getDesignation() {
return designation;
}

public void setDesignation(String designation) {
this.designation = designation;
}

public String getAddress() {
return address;
}

public void setAddress(String address) {
this.address = address;
}

}

Here we are using annotation for mapping our table employee to our class Employee.java.

Step3.  Utility class:  Now create an util class as HibernateUtil.java

package net.roseindia.util;

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

public class HibernateUtil {
	private static SessionFactory sessionFactory;

	static {
		try {
			sessionFactory = new AnnotationConfiguration().configure()
					.buildSessionFactory();

		} catch (HibernateException exception) {
			exception.printStackTrace();
		}
	}

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

Step 4. Main Class:  Now we are going to create our main class.Here we are inserting data in to employee table. session.save(employee) saves the employee object into the database table.

package net.roseindia.application;

import net.roseindia.table.Employee;
import net.roseindia.util.HibernateUtil;

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

public class MainClaz {
public static void main(String[] args) {

SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
Employee employee = new Employee();
employee.setEmpName("Rose");
employee.setAddress("Patna");
employee.setSalary(18000);
employee.setDesignation("Manager");
session.save(employee);
transaction.commit();
session.clear();
session.close();
sessionFactory.close();

}
}

Output:

Hibernate: select employee0_.empId as empId0_0_, employee0_.address as address0_0_, employee0_.designation as designat3_0_0_, employee0_.emp_name as emp4_0_0_, employee0_.emp_salary as emp5_0_0_ from employee employee0_ where employee0_.empId=?
Hibernate: insert into employee (address, designation, emp_name, emp_salary) values (?, ?, ?, ?)

Download source code