In Spring Boot, you don’t usually build or manage a SessionFactory manually. Instead, Spring Boot autoconfigures Hibernate and manages the SessionFactory for you, thanks to its integration with Spring Data JPA or the Hibernate starter.
🔹 How it works in Spring Boot:
- When you add dependencies like
spring-boot-starter-data-jpa, Spring Boot:- Automatically creates an
EntityManagerFactory(the JPA equivalent ofSessionFactory). - Under the hood, this
EntityManagerFactoryis backed by Hibernate’sSessionFactory. - You rarely interact directly with the
SessionFactory— you work with Spring Data repositories,EntityManager, or@Transactionalservices instead.
- Automatically creates an
🔹 Getting the SessionFactory if you need it:
If you really need to access Hibernate’s native SessionFactory, you can get it from the JPA EntityManager like this:
@Autowired
private EntityManager entityManager;
public void doSomething() {
Session session = entityManager.unwrap(Session.class);
// Now you have direct access to the Hibernate Session.
}
Or get the SessionFactory itself:
@Autowired
private EntityManagerFactory entityManagerFactory;
public void printSessionFactoryInfo() {
SessionFactory sessionFactory = entityManagerFactory.unwrap(SessionFactory.class);
System.out.println("SessionFactory: " + sessionFactory);
}
🔹 Key advantages of Spring Boot integration:
✅ Handles SessionFactory lifecycle automatically — built at startup, closed on shutdown.
✅ Configures connection pool (HikariCP), dialect, caching, and more based on application.properties.
✅ Enables declarative transactions via @Transactional without manual session or transaction handling.
✅ Key takeaway:
In Spring Boot, you don’t need to create or manage SessionFactory manually — Spring Boot and Spring Data JPA abstract it away, while still giving you the option to access it if needed for advanced scenarios.