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 :-
oracle.jdbc.driver.OracleDriver
org.hibernate.dialect.Oracle9Dialect
jdbc:oracle:thin:@localhost:1521:xe
system
oracle
update
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();
}
}