SessionFactory is the thread-safe factory Hibernate uses to produce Session objects — it's built once from the Configuration and holds all the compiled entity mappings and settings needed to talk to a particular database.
Key Points: • It is a heavyweight object, expensive to create, so applications typically build exactly one per data source at startup and reuse it. • Unlike Session, SessionFactory is thread-safe and can be shared freely across the whole application. • It holds the second-level cache (if enabled) and compiled mapping metadata used to generate SQL. • openSession() is the primary method used to obtain a new, per-unit-of-work Session from it. • Closing a SessionFactory releases all underlying resources, including connection pools, and should generally happen only at application shutdown.
Example: A Spring Boot application typically wires up exactly one SessionFactory (or, via JPA, one EntityManagerFactory) as a singleton bean at startup, and every request or service method then calls it to get a fresh Session for that unit of work.
Interview Tip: A concise interview answer is:
"SessionFactory is a heavyweight, thread-safe object built once from Hibernate's Configuration, and its job is to produce lightweight Session instances via openSession(). You create it once per application or data source and reuse it for the app's lifetime, unlike Session, which you open and close per unit of work."