SessionFactory
in Hibernate with Spring Boot using a MySQL database. We will use the Employee
entity for this example.Introduction
Spring Boot makes it easy to create stand-alone, production-grade Spring-based applications. By integrating Hibernate with Spring Boot, you can leverage the powerful ORM capabilities of Hibernate with the ease of configuration provided by Spring Boot. The SessionFactory
in Hibernate is used to create sessions that manage database operations.
In this tutorial, we will:
- Set up a Spring Boot project with Hibernate and MySQL dependencies.
- Configure Hibernate in a Spring Boot application.
- Create an entity class (
Employee
). - Implement an example to demonstrate the use of
SessionFactory
in Spring Boot. - Demonstrate the
SessionFactory
usage using a sample application.
Step 1: Set Up Your Spring Boot Project
1.1 Create a Spring Boot Project
You can create a Spring Boot project using Spring Initializr or your IDE's Spring Boot project creation feature.
1.2 Add Dependencies
Update your pom.xml
file to include the necessary dependencies for Spring Boot, Hibernate, and MySQL.
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>hibernate-sessionfactory-springboot</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<!-- Spring Boot Starter Data JPA -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- MySQL Connector -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.29</version>
</dependency>
<!-- Spring Boot Starter Web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Spring Boot Starter Test -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Step 2: Configure Hibernate in Spring Boot
2.1 Create application.properties
Create an application.properties
file in the src/main/resources
directory to configure database connection settings and Hibernate properties.
# MySQL Database Configuration
spring.datasource.url=jdbc:mysql://localhost:3306/hibernate_db
spring.datasource.username=root
spring.datasource.password=password
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
# Hibernate Configuration
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQLDialect
Replace hibernate_db
, root
, and password
with your MySQL database name and credentials.
2.2 Create a Configuration Class
Create a configuration class to define the SessionFactory
bean.
package com.example.config;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
import javax.sql.DataSource;
import java.util.Properties;
@Configuration
public class HibernateConfig {
@Autowired
private DataSource dataSource;
@Bean
public LocalSessionFactoryBean sessionFactory() {
LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
sessionFactory.setDataSource(dataSource);
sessionFactory.setPackagesToScan("com.example.entity");
sessionFactory.setHibernateProperties(hibernateProperties());
return sessionFactory;
}
private Properties hibernateProperties() {
Properties properties = new Properties();
properties.put("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
properties.put("hibernate.show_sql", "true");
properties.put("hibernate.format_sql", "true");
properties.put("hibernate.hbm2ddl.auto", "update");
return properties;
}
}
Explanation:
- The
sessionFactory
method creates and configures aLocalSessionFactoryBean
which provides aSessionFactory
. - The
hibernateProperties
method sets additional Hibernate properties.
Step 3: Create the Entity Class
Create an entity class Employee
that will be mapped to a table in the database. This class uses annotations to define the entity and its fields.
package com.example.entity;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
@Entity
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String department;
private double salary;
// Getters and setters
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDepartment() {
return department;
}
public void setDepartment(String department) {
this.department = department;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
}
Explanation:
- The
@Entity
annotation specifies that the class is an entity and is mapped to a database table. - The
@Id
annotation specifies the primary key of the entity. - The
@GeneratedValue(strategy = GenerationType.IDENTITY)
annotation specifies that the primary key is auto-incremented.
Step 4: Demonstrate the Use of SessionFactory
Create a MainApp
class to demonstrate the use of SessionFactory
. This class initializes the SessionFactory
, opens a session, performs an operation, and then closes the session and shuts down the SessionFactory
.
4.1 Create a Service Class
Create a service class to demonstrate the use of SessionFactory
.
package com.example.service;
import com.example.entity.Employee;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
public class EmployeeService {
@Autowired
private SessionFactory sessionFactory;
@Transactional
public void saveEmployee(Employee employee) {
Session session = sessionFactory.getCurrentSession();
session.save(employee);
}
}
Explanation:
- The
EmployeeService
class demonstrates the use ofSessionFactory
to obtain aSession
and perform an operation. - The
saveEmployee
method uses theSession
to save anEmployee
entity.
4.2 Create a Controller Class
Create a controller class to expose an endpoint to demonstrate the use of SessionFactory
.
package com.example.controller;
import com.example.entity.Employee;
import com.example.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class EmployeeController {
@Autowired
private EmployeeService employeeService;
@GetMapping("/saveEmployee")
public String saveEmployee(@RequestParam String name, @RequestParam String department, @RequestParam double salary) {
Employee employee = new Employee();
employee.setName(name);
employee.setDepartment(department);
employee.setSalary(salary);
employeeService.saveEmployee(employee);
return "Employee saved successfully";
}
}
Explanation:
- The
EmployeeController
class exposes an endpoint to save an employee. - The
/saveEmployee
endpoint takesname
,department
, andsalary
as request parameters and calls thesaveEmployee
method ofEmployeeService
.
4.3 Run the Application
Create a main application class to run the Spring Boot application.
package com.example;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class HibernateSessionFactorySpringBootApplication {
public static void main(String[] args) {
SpringApplication.run(HibernateSessionFactorySpringBootApplication.class, args);
}
}
Explanation:
- The
HibernateSessionFactorySpringBootApplication
class is the entry point of the Spring Boot application. - The
main
method runs the Spring Boot application.
Step 5: Test the Application
Run the Spring Boot application and test the /saveEmployee
endpoint using a tool like Postman or a web browser. For example:
http://localhost:8080/saveEmployee?name=John%20Doe&department=IT&salary=5000.00
Sample Output
When you access the
endpoint, you should see the following response:
Employee saved successfully
This output indicates that the employee was successfully saved using Hibernate's SessionFactory
.
Conclusion
In this tutorial, we have successfully demonstrated how to use SessionFactory
in a Spring Boot application with Hibernate. We set up a Spring Boot project, configured Hibernate, created an entity class, implemented a service class to demonstrate the use of SessionFactory
, and demonstrated the usage with a sample application. This guide provides a solid foundation for managing Hibernate sessions using SessionFactory
in your Spring Boot applications.
Comments
Post a Comment