Latest Tutorials| Questions and Answers|Ask Questions?|Site Map



Home Hibernate Hibernate4 Hibernate SessionFactory Example

Related Tutorials


 
 

Share on Google+Share on Google+

Hibernate SessionFactory Example

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

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

If you enjoyed this post then why not add us on Google+? Add us to your Circles



Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: March 31, 2012

Related Tutorials

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?
DMCA.com