Hibernate SessionFactory Example

In this example, we will learn about the getting session instance from the SessionFactory interface in Hibernate 4.

Hibernate SessionFactory Example

Hibernate SessionFactory Example

In this example, we will learn about the getting session instance from the SessionFactory  interface in Hibernate 4.

The core purpose of org.hibernate.SessionFactory is to get org.hibernate.Session instances. The org.hibernate.SessionFactory is a thread-safe global object which is instantiated once and and threads servicing client requests obtain Session instances from this factory.

Previously, we get the Session instance by instantiating SessionFactory instance as follows :

SessionFactory sessionFactory = 
new AnnotationConfiguration().configure().buildSessionFactory();
Session session = sessionFactory.getCurrentSession();

But in the Hibernate 4, the method buildSessionFactory() from the type Configuration is deprecated.

In the below example, you will learn how to get the Session instance by instantiating SessionFactory instance in Hibernate 4 :

The project hierarchy and the jar files used is given below :

CODE

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>

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;
}
}

HibernateSessionFactory.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 HibernateSessionFactory {
private static SessionFactory factory;
private static ServiceRegistry serviceRegistry;

public static void main(String[] args) {
try {
Configuration configuration = new Configuration();
configuration.configure()
.setProperty("hibernate.show_sql", "false");
;
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);
}
System.out.println("**Example : Hibernate 4 SessionFactory**");
System.out.println("----------------------------------------");
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.println("First Name: " + worker.getFirstName());
System.out.println("Last Name: " + worker.getLastName());
System.out.println("Salary: " + worker.getSalary());
System.out.println("----------------------------------------");
}
tx.commit();
} catch (HibernateException e) {
if (tx != null)
tx.rollback();
e.printStackTrace();
} finally {
session.close();
}
}
}

OUTPUT

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

**Example : Hibernate 4 SessionFactory**
----------------------------------------
First Name: Kumar
Last Name: Dhawan
Salary: 5000
----------------------------------------
First Name: Rudra
Last Name: Shah
Salary: 15000
----------------------------------------

Download Source Code