Spring Boot
Hibernate
SessionFactory
Java
ORM

Spring Boot - Handle to Hibernate SessionFactory

System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design

Spring Boot is one of the most popular frameworks for building Java applications, and Hibernate is a leading ORM framework used to map Java objects to database tables. When working with Spring Boot and Hibernate, one of the essential components is the SessionFactory. This component is responsible for creating Session objects, which are the primary interfaces for interacting with the database. In this article, we will explore how to handle Hibernate SessionFactory in a Spring Boot application.

Understanding Hibernate SessionFactory

The SessionFactory is a heavyweight object, designed to be created once per application lifetime. It is responsible for the lifecycle of Session instances, which facilitate CRUD operations against a database. In a typical Spring Boot application, the management of SessionFactory is seamlessly integrated with the Spring context.

Key Characteristics of SessionFactory

  • Heavyweight Object: Designed to be instantiated once and reused across the application.
  • Thread Safety: Can be shared among multiple threads of an application.
  • Configuration Holder: Contains database connection, caching, and configuration settings.

Integrating Hibernate with Spring Boot

Spring Boot simplifies the setup of SessionFactory through its auto-configuration capabilities. Below are the steps to configure Hibernate SessionFactory in a Spring Boot application.

Step 1: Add Dependencies

You need to include the following dependencies in your pom.xml for a Maven project:

xml
1<dependency>
2    <groupId>org.springframework.boot</groupId>
3    <artifactId>spring-boot-starter-data-jpa</artifactId>
4</dependency>
5<dependency>
6    <groupId>org.springframework.boot</groupId>
7    <artifactId>spring-boot-starter-web</artifactId>
8</dependency>
9<dependency>
10    <groupId>com.h2database</groupId>
11    <artifactId>h2</artifactId>
12    <scope>runtime</scope>
13</dependency>

These dependencies will add JPA and Hibernate support, and H2 as an in-memory database for testing.

Step 2: Spring Boot Configuration

In the application.properties file, configure the database connection and Hibernate settings:

properties
1spring.datasource.url=jdbc:h2:mem:testdb
2spring.datasource.driver-class-name=org.h2.Driver
3spring.datasource.username=sa
4spring.datasource.password=
5
6spring.jpa.hibernate.ddl-auto=update
7spring.jpa.show-sql=true

Step 3: Configure SessionFactory

Spring Boot automatically configures the SessionFactory using the beans defined in your project. However, if you need more control over the configuration, you can define a SessionFactory bean explicitly:

java
1import org.hibernate.SessionFactory;
2import org.springframework.boot.autoconfigure.orm.jpa.EntityManagerFactoryBuilder;
3import org.springframework.context.annotation.Bean;
4import org.springframework.context.annotation.Configuration;
5import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
6
7import javax.persistence.EntityManagerFactory;
8import org.springframework.beans.factory.annotation.Autowired;
9
10@Configuration
11public class HibernateConfig {
12
13    @Autowired
14    private EntityManagerFactory entityManagerFactory;
15
16    @Bean
17    public SessionFactory sessionFactory() {
18        if (entityManagerFactory.unwrap(SessionFactory.class) == null) {
19            throw new NullPointerException("factory is not a hibernate factory");
20        }
21        return entityManagerFactory.unwrap(SessionFactory.class);
22    }
23}

Using the SessionFactory

Once you have the SessionFactory configured, you can use it in your DAO class to handle database operations:

java
1import org.hibernate.Session;
2import org.hibernate.SessionFactory;
3import org.springframework.beans.factory.annotation.Autowired;
4import org.springframework.stereotype.Repository;
5import org.springframework.transaction.annotation.Transactional;
6
7import java.util.List;
8
9@Repository
10@Transactional
11public class UserDao {
12
13    @Autowired
14    private SessionFactory sessionFactory;
15
16    public List<User> getAllUsers() {
17        Session session = sessionFactory.getCurrentSession();
18        return session.createQuery("from User", User.class).list();
19    }
20
21    public void saveUser(User user) {
22        Session session = sessionFactory.getCurrentSession();
23        session.saveOrUpdate(user);
24    }
25
26    // Additional CRUD operations...
27}

In the above example, the @Transactional annotation is used to manage transactions implicitly.

Summary Table

Here is a table summarizing important points about the integration of Hibernate SessionFactory with a Spring Boot application:

Feature/ConceptDescription
SessionFactoryHeavyweight, thread-safe object. Handles Session lifecycle and configurations.
Spring Boot SetupSimplifies Hibernate integration using starter dependencies.
ConfigurationDefault through application.properties. Can be customized in Java Config.
DAO ImplementationUse @Autowired and @Transactional for seamless integration.
Session UsageUse sessionFactory.getCurrentSession() to perform DB operations.

Additional Considerations

  • Connection Pooling: Out of the box, Spring Boot provides a suitable connection pool (e.g., HikariCP) which can be configured for better performance in production.
  • Caching: Hibernate supports both first-level and second-level caching, which can be configured for performance optimization.
  • Transactions: Proper management of transactions is crucial, use @Transactional wisely to ensure database integrity.
  • Testing: Use an embedded database like H2 for easier testing of application logic involving database operations.

In conclusion, the integration of Hibernate with Spring Boot is straightforward and efficient due to Spring Boot's auto-configuration features. Understanding how to manage the SessionFactory will empower you to build flexible and robust database-driven applications.


Related reading
Course
Beginner
27 lessons
10 hours
System Design Fundamentals

Build a strong foundation in designing scalable, reliable distributed systems.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design

All Rights Reserved.