Java.Hibernate.Beginner.What about Session Fatory in Spring Boot ?

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 of SessionFactory).
    • Under the hood, this EntityManagerFactory is backed by Hibernate’s SessionFactory.
    • You rarely interact directly with the SessionFactory — you work with Spring Data repositories, EntityManager, or @Transactional services instead.

🔹 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.

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