Menu

SessionFactory and Session

SessionFactory and Session

Two Objects, Two Roles

SessionFactory and Session are the two objects you use in almost every Hibernate program. They differ in cost, lifetime, and thread safety.

 

SessionFactory

Session

PurposeHolds configuration and mappings, creates sessionsPerforms database work for one unit of work
Cost to createHighLow
Thread safeYesNo
LifetimeOne per database, for the whole applicationShort, for one operation or request

A Session wraps a JDBC connection and holds the persistence context, which we cover in the next lesson. Never share a session between threads.

Creating and Using Them

SessionFactory sessionFactory = new Configuration()
        .configure()
        .buildSessionFactory();

try (Session session = sessionFactory.openSession()) {
    Student student = session.find(Student.class, 1L);
}

sessionFactory.close();

Code Explanation:

  • configure() reads hibernate.cfg.xml from the classpath.
  • buildSessionFactory() validates the mappings and prepares Hibernate, so it should run once at startup.
  • openSession() returns a new session, and try-with-resources closes it when the block ends.
  • find() loads a Student by primary key and returns null if no row exists.
  • The factory is closed at application shutdown to release its resources.

Hibernate Tutorial

AP

Abhishek Pati



Learn via Video Course

Java Programming ( Telugu) Logo

Java Programming ( Telugu)

11 hrs



Get in Touch For Details