What is SessionFactory in Hibernate?

SessionFactory :-

  • A SessionFactory produces Hibernate Sessions.
  • A SessionFactory represents an “instance” of Hibernate.
  • SessionFactory is an interface and SessionFactorylmpl will be the implemented class.
  • It is heavy weight object that has to be created only once per application. SessionFactory object provides lightweight Session objects.
  • SessionFactory is not a singleton class. Lets create it only once using per Helper class
  • We need one SessionFactory object created as per database. So if we are using multiple databases then we have to create multiple SessionFactory objects.
  • SessionFactory interface is also responsible for second-level caching.
  • It is a Thread safe object.
  • It is factory of Session objects.

              Syntax :-   public interface SessionFactory extends EntityManagerFactory

         We are using Hibernate SessionFactory inside hibernate.cfg.xml file as below :-

				
					<?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>
              <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
            <property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>  
            <property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</property>  
            <property name="connection.username">system</property>  
            <property name="connection.password">oracle</property>
            <property name="hbm2ddl.auto">update</property>
        <mapping resource="employee.hbm.xml"/>
       <mapping resource="address.hbm.xml"/>   
        </session-factory>
      </hibernate-configuration>
				
			

      We are using Hibernate SessionFactory inside Main Application class file as below :-

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

public class EmployeeMain {
	public static void main(String[] args) {
		Configuration cfg = new Configuration();
		cfg.configure("hibernate.cfg.xml");
		SessionFactory sessionFactory = cfg.buildSessionFactory();
		Session session = sessionFactory.openSession();
		Transaction tx = session.beginTransaction();
		Employee e1 = new Employee();
		e1.setName("Ravi Malik");
		session.persist(e1);
		tx.commit();
		session.close();
	}
}