Spring Boot - Handle to Hibernate SessionFactory

Last Updated : 1 May, 2026

In Spring Boot, Hibernate SessionFactory is the core interface used to create and manage database sessions. While Spring Boot commonly uses JPA (EntityManager), direct access to SessionFactory is useful for advanced Hibernate features and fine-grained control over database operations.

  • Provides low-level access to Hibernate session management
  • Useful for performance tuning and custom queries
  • Enables direct interaction with Hibernate APIs

SessionFactory

SessionFactory is a thread-safe object in Hibernate responsible for creating Session instances, which are used to interact with the database.

  • One SessionFactory is typically created per application
  • It is heavy-weight and initialized at startup
  • Internally manages connection pooling and caching

Why Use SessionFactory in Spring Boot?

Although Spring Boot prefers JPA, using SessionFactory can be beneficial when:

  • We need Hibernate-specific features not available in JPA
  • We want better control over session and transaction handling
  • We are working with legacy Hibernate-based applications

Key Terminologies:

  • HibernateSessionFactory: A thread-safe object created at application startup and used throughout the lifecycle. It manages database connections and entity mappings.
  • JPA: A Java specification for managing and persisting data between objects and relational databases. It provides interfaces and annotations for CRUD operations.
  • Datasource: An interface in JDBC used to establish database connections. It provides connections that Hibernate uses for database operations.
  • Hibernate Dialect: A configuration that defines the SQL dialect of the underlying database. It helps Hibernate generate database-specific queries.
  • Hibernate Properties: Configuration settings used to customize Hibernate behavior. They control aspects like connection, caching, and logging.

Step-by-step implementation

By the following these steps, developers can effectively can manage the Hibernate SessionFactory in the Spring Boot applications and it can ensure the optimal database interaction and the streamlined the performance.

  1. Configure the Hibernate Properties: Define Hibernate and datasource properties in application.properties or application.yml. This includes database URL, credentials, dialect, and ddl-auto settings.
  2. Define the Entity Classes: Create entity classes that represent database tables. Use @Entity and related annotations to define primary keys, relationships, and mappings.
  3. Create the Spring Application: Create the main class annotated with @SpringBootApplication. This bootstraps and runs the Spring Boot application.
  4. Configure SessionFactory Bean: Create a configuration class annotated with @Configuration to manage the SessionFactory. Use EntityManagerFactory.unwrap(SessionFactory.class) to obtain it.
  5. Inject the SessionFactory: Inject the SessionFactory into service or repository classes. Use sessionFactory.getCurrentSession() to perform database operations within transactions.

Project to handle to Hibernate SessionFactory in the Spring application

Now, we will demonstrate how to the handle to Hibernate SessionFactory in the Spring application.

Step 1: Create Spring Boot Project

Create a project using Spring STS/Initializer with the following dependencies:

  • Spring Web
  • Spring Data JPA
  • Lombok
  • MySQL Driver

Once complete the creation of the spring project then the spring project file structure look like the below image.

File Structure

Step 2: Configure application.properties

Open application.properties file, and write the below code for the server port and mongodb database configuration to the project.

spring.application.name=HibernateSessionFactory
server.port=8082

# Database Configuration
spring.datasource.url=jdbc:mysql://localhost:3306/example
spring.datasource.username=root
spring.datasource.password=

# Hibernate Configuration
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
spring.jpa.hibernate.ddl-auto=update

Step 3: Create Entity Class (Product)

Create the new package and it named as the model in that package create the new Java class and it named as Product.

Go to src > org.example.hibernatesessionfacotry > model > Product and put the below code.

Java
package org.example.hibernatesessionfactory.model;

import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Entity
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Product {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
    private double price;

}

Step 4: Create Repository Layer

Create a new package and named it as the repository. In that package, create the new Java interface and named it as ProductRepository.

Go to src > org.example.hibernatesessionfacotry > repository > ProductRepository and put the below code.

Java
package org.example.hibernatesessionfactory.repository;

import org.example.hibernatesessionfactory.model.Product;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface ProductRepository extends JpaRepository<Product, Long> {

    /**
     * Repository interface for accessing Product entities.
     * Extends JpaRepository to provide CRUD operations for Product entities.
     */
}

Step 5: Configure Hibernate

Create the new package and it named as the configuration in that package create the new Java class and it named as HibernateConfig.

Go to src > org.example.hibernatesessionfacotry > configuration > HibernateConfig and put the below code.

Java
package org.example.hibernatesessionfactory.configuration;

import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(basePackages = "org.example.hibernatesessionfactory.repository")
public class HibernateConfig {

    /**
     * Configuration class for Hibernate.
     */
}

Step 6: Create Service Layer

Create the new package and it named as the service in that package create the new Java class and it named as ProductService.

Go to src > org.example.hibernatesessionfacotry > service > ProductService and put the below code.

Java
package org.example.hibernatesessionfactory.service;

import jakarta.transaction.Transactional;
import org.example.hibernatesessionfactory.model.Product;
import org.example.hibernatesessionfactory.repository.ProductRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class ProductService {

    @Autowired
    private ProductRepository productRepository;

    @Transactional
    public Product saveProduct(Product product) {
        return productRepository.save(product);
    }

    public List<Product> getAllProducts() {
        return productRepository.findAll();
    }
}

Step 7: Create Controller Layer

Create a new package named as the controller, in that package, create the new Java class and it named as ProductController.

Go to src > org.example.hibernatesessionfacotry > controller > ProductController and put the below code.

Java
package org.example.hibernatesessionfactory.controller;

import org.example.hibernatesessionfactory.model.Product;
import org.example.hibernatesessionfactory.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/products")
public class ProductController {

    @Autowired
    private ProductService productService;

    /**
     * Creates a new product.
     */
    @PostMapping
    public Product createProduct(@RequestBody Product product) {
        return productService.saveProduct(product);
    }

    /**
     * Retrieves all products.
     */
    @GetMapping
    public List<Product> getAllProducts() {
        return productService.getAllProducts();
    }
}

Step 8: Main Application Class

Open the main class and write the below code.

Java
package org.example.hibernatesessionfactory;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class HibernateSessionFactoryApplication {

    public static void main(String[] args) {
        SpringApplication.run(HibernateSessionFactoryApplication.class, args);
    }

}

Step 9: Run the Application

After completing the project, it will run as spring application and once it runs successfully, then it starts at port 8082.

log output

Output

Save Product Endpoint:

POST http://localhost:8082/products

Output in Postman:

saveAPI


GET the Products Endpoint:

GET http://localhost:8082/products

Output in Postman:

GetAPI

If we follow the above steps, then we can demonstrate how to the handle to the Hibernate SessionFactory of the Spring application.

Comment

Explore