Hibernate SessionFactory Example

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


 

Ads

Tutorials   
How to write hello world example program in Hibernate? How to create one to one relationship in Hibernate 4 with Annotation? How to calculate minimum in Hibernate using the min() Function Hibernate 4.3.4 Released: Hibernate 4.3.4.Final Maven dependency Hibernate 4.3 Hello World: Example How to create SessionFactory in Hibernate 4.3.1? Hibernate 4 Hello World: Example of Hello World program Hibernate 4 create Session Factory: Example of creating Session Factory in Hibernate 4 Hibernate 4.3 and JPA 2.1 Example What is Hibernate in Java? Hibernate Overview and Architecture What is JPA 2.1? Hibernate 4.3.0.Final Maven dependency Hibernate 4.3 ORM Features Hibernate 4.3 Tutorial Hibernate Criteria average example Hibernate Criteria load all objects from table Hibernate Criteria Hibernate beginner tutorial Hibernate Session.delete() Example Hibernate save or update method example Hibernate Load Example Hibernate save Example - Rose India Hibernate 4 tutorials Hibernate Example Step by Step in Eclipse Hibernate Configuration files Setup Hibernate Environment Hibernate Architecture Hibernate Overview Hibernate 4.2 Tutorial Hibernate 4 Annotations Tutorial Hibernate 4 AnnotationSessionFactoryBean hibernate versions hibernate jndi hibernate tomcat hibernate metamodel generator hibernate entity Seam Hibernate C3P0 Hibernate hibernate shard hibernate means temporal hibernate jsf hibernate spring j2ee hibernate spring hibernate encrypted password alias_to_entity_map hibernate temporal jsf spring hibernate hibernate by example hibernate repository hibernate sample code
Ads

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

Advertisements

Ads
Share on Google+Share on Google+

Hibernate SessionFactory Example

Posted on: March 31, 2012 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Advertisements

 

Discuss: Hibernate SessionFactory Example  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments:3
Avishek
October 21, 2012
Session Factory

Hi! Its written SessionFactory can be instantiated once but if its an interface, how can it be instantiated. Pardom me, if my knowledge is less in Java...
usefull
April 27, 2013
usefull

usefull
Sofiane
January 9, 2014
ClassCastException when executing this class

Hi, I'm getting Failed to create sessionFactory object.java.lang.ClassCastException: org.hibernate.annotations.common.reflection.java.JavaReflectionManager cannot be cast to org.hibernate.annotations.common.reflection.MetadataProviderInjector Exception in thread "main" java.lang.ExceptionInInitializerError at com.immoscanner.tools.hibernate.HibernateSessionFactory.main(HibernateSessionFactory.java:28) Caused by: java.lang.ClassCastException: org.hibernate.annotations.common.reflection.java.JavaReflectionManager cannot be cast to org.hibernate.annotations.common.reflection.MetadataProviderInjector at org.hibernate.cfg.Configuration.createReflectionManager(Configuration.java:2939) at org.hibernate.cfg.Configuration.createReflectionManager(Configuration.java:2934) at org.hibernate.cfg.Configuration.reset(Configuration.java:305) at org.hibernate.cfg.Configuration.<init>(Configuration.java:296) at org.hibernate.cfg.Configuration.<init>(Configuration.java:300) at com.immoscanner.tools.hibernate.HibernateSessionFactory.main(HibernateSessionFactory.java:21) When trying to execute this class. Here is my dependencies in my pom: <dependencies> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>4.2.7.Final</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.7.5</version> </dependency> </dependencies> Could you please help?

Ads

 

Ads