Java.Hibernate.Beginner.What is a SessionFactory?

What is a SessionFactory in Hibernate?

Answer:
A SessionFactory is a heavyweight, thread-safe Hibernate object responsible for:

  • Creating Session instances, which are the primary interface for interacting with the database.
  • Managing configuration settings like database connection details, entity mappings, and caching strategies.
  • Acting as a factory for sessions, typically shared across your entire application.

🔹 Key characteristics:
✅ Built once and reused: you should create a SessionFactory at application startup and reuse it throughout the app’s lifetime.
✅ Thread-safe: safe for concurrent access by multiple threads.
✅ Expensive to build: since it parses mappings and sets up services, avoid recreating it frequently.
✅ Immutable: once built, its configuration cannot be changed — you’d need to rebuild it if your configuration changes.


🔹 Example usage:

SessionFactory sessionFactory = new Configuration()
    .configure("hibernate.cfg.xml") // loads settings from config file
    .buildSessionFactory();

Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();

User user = session.get(User.class, 1L);
System.out.println("Found user: " + user.getUsername());

tx.commit();
session.close();

sessionFactory.close(); // typically done on application shutdown

🔹 Common best practice:

  • In web apps, create one SessionFactory during application startup (e.g., in a ServletContextListener or Spring Boot’s startup).
  • Don’t create a new SessionFactory per request or per transaction — it’s too costly.

Key takeaway:
The SessionFactory is the main entry point to Hibernate, responsible for building sessions and bootstrapping your ORM configuration; it should be a singleton in your application.

This entry was posted in Без рубрики. Bookmark the permalink.