Hibernate 4 Simple Example

This section contains a simple Hibernate 4 example using Annotation with source code. The eclipse id and Apache Tomcat is used in this example.

Hibernate 4 Simple Example

Hibernate 4 Simple Example

This section contains a simple Hibernate 4 example using Annotation with source code. The eclipse id and Apache Tomcat is used in this example.

In Hibernate 4, buildSessionFactory( ) is deprecated. This example contains code which you can use in spite of buildSessionFactory ().

The project hierarchy is given below :

Here is the video instruction for developing and running the example in Eclipse:

The jar file used in this example is given below :

The database query used to create database is :

create table WORKER (
id INT NOT NULL auto_increment,
first_name VARCHAR(20) default NULL,
last_name VARCHAR(20) default NULL,
salary INT default NULL,
PRIMARY KEY (id)
);

hibernate.cfg.xml

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/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://192.168.10.13:3306/ankdb</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="worker.Worker" />

</session-factory>
</hibernate-configuration>

POJO class( Worker.java )

package worker;

import javax.persistence.*;

@Entity
@Table(name = "Worker")
public class Worker {
@Id
@GeneratedValue
@Column(name = "id")
private int id;

@Column(name = "first_name")
private String firstName;

@Column(name = "last_name")
private String lastName;

@Column(name = "salary")
private int salary;

public Worker() {
}

public Worker(String fname, String lname, int salary) {
this.firstName = fname;
this.lastName = lname;
this.salary = salary;
}

public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}


public String getFirstName() {
return firstName;
}

public void setFirstName(String first_name) {
this.firstName = first_name;
}

public String getLastName() {
return lastName;
}

public void setLastName(String last_name) {
this.lastName = last_name;
}

public int getSalary() {
return salary;
}

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

Application class( HandlingWorker.java )

package worker;

import java.util.List;
import java.util.Iterator; 

import org.hibernate.HibernateException; 
import org.hibernate.Session; 
import org.hibernate.Transaction;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;


public class HandlingWorker {
private static SessionFactory factory;
private static ServiceRegistry serviceRegistry;

public static void main(String[] args) {
try{
Configuration configuration = new Configuration();
configuration.configure();
serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry(); 
factory = configuration.buildSessionFactory(serviceRegistry);
}catch (Throwable ex) { 
System.err.println("Failed to create sessionFactory object." + ex);
throw new ExceptionInInitializerError(ex); 
}
HandlingWorker handle = new HandlingWorker();

/* Add few worker records in database */
Integer worker1 = handle.addWorker("Ram", "Prasad", 1000);
Integer worker2 = handle.addWorker("Rahul", "Das", 5000);
Integer worker3 = handle.addWorker("Steven", "Abraham", 10000);

/* List down all the workers */
handle.listWorkers();

/* Update worker's records */
handle.updateWorker(worker1, 5000);

/* Delete an worker from the database */
handle.deleteWorker(worker2);

/* List down new list of the workers */
handle.listWorkers();
}
/* Method to CREATE an worker in the database */
public Integer addWorker(String fname, String lname, int salary){
Session session = factory.openSession();
Transaction tx = null;
Integer workerID = null;
try{
tx = session.beginTransaction();
Worker worker = new Worker(fname, lname, salary);
workerID = (Integer) session.save(worker); 
tx.commit();
}catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace(); 
}finally {
session.close(); 
}
return workerID;
}
/* Method to READ all the employees */
public void listWorkers( ){
Session session = factory.openSession();
Transaction tx = null;
try{
tx = session.beginTransaction();
List employees = session.createQuery("FROM Worker").list(); 
for (Iterator iterator = 
employees.iterator(); iterator.hasNext();){
Worker worker = (Worker) iterator.next(); 
System.out.print("First Name: " + worker.getFirstName()); 
System.out.print(" Last Name: " + worker.getLastName()); 
System.out.println(" Salary: " + worker.getSalary()); 
}
tx.commit();
}catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace(); 
}finally {
session.close(); 
}
}
/* Method to UPDATE salary for an worker */
public void updateWorker(Integer WorkerID, int salary ){
Session session = factory.openSession();
Transaction tx = null;
try{
tx = session.beginTransaction();
Worker worker = 
(Worker)session.get(Worker.class, WorkerID); 
worker.setSalary( salary );
session.update(worker); 
tx.commit();
}catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace(); 
}finally {
session.close(); 
}
}
/* Method to DELETE an worker from the records */
public void deleteWorker(Integer WorkerID){
Session session = factory.openSession();
Transaction tx = null;
try{
tx = session.beginTransaction();
Worker worker = 
(Worker)session.get(Worker.class, WorkerID); 
session.delete(worker); 
tx.commit();
}catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace(); 
}finally {
session.close(); 
}
}
}

OUTPUT

When you execute the above example you will get the following output in console :

Hibernate: insert into Worker (first_name, last_name, salary) values (?, ?, ?)
Hibernate: insert into Worker (first_name, last_name, salary) values (?, ?, ?)
Hibernate: insert into Worker (first_name, last_name, salary) values (?, ?, ?)
Hibernate: select worker0_.id as id0_, worker0_.first_name as first2_0_, worker0_.last_name 
as last3_0_, worker0_.salary as salary0_ from Worker worker0_
First Name: Ram Last Name: Prasad Salary: 1000
First Name: Rahul Last Name: Das Salary: 5000
First Name: Steven Last Name: Abraham Salary: 10000
Hibernate: select worker0_.id as id0_0_, worker0_.first_name as first2_0_0_, worker0_.last_name 
as last3_0_0_, worker0_.salary as salary0_0_ from Worker worker0_ where worker0_.id=?
Hibernate: update Worker set first_name=?, last_name=?, salary=? where id=?
Hibernate: select worker0_.id as id0_0_, worker0_.first_name as first2_0_0_, worker0_.last_name 
as last3_0_0_, worker0_.salary as salary0_0_ from Worker worker0_ where worker0_.id=?
Hibernate: delete from Worker where id=?
Hibernate: select worker0_.id as id0_, worker0_.first_name as first2_0_, worker0_.last_name 
as last3_0_, worker0_.salary as salary0_ from Worker worker0_
First Name: Ram Last Name: Prasad Salary: 5000
First Name: Steven Last Name: Abraham Salary: 10000

Download Source Code