Open In App

Spring Boot - Database Integration (JPA, Hibernate, MySQL, H2)

Last Updated : 20 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In modern application development, integrating a database is crucial for persisting and managing data. Spring Boot simplifies this process by providing seamless integration with various databases through JPA (Java Persistence API) and Hibernate ORM (Object-Relational Mapping). This article will guide you through setting up database integration in a Spring Boot application using JPA with Hibernate, covering both MySQL and H2 in-memory databases.

Database Integration in Spring Boot using JPA, Hibernate, MySQL, and H2

In a Spring Boot application, database integration is essential for storing, retrieving, updating, and managing data. This integration is primarily achieved using JPA, Hibernate, and an underlying database like MySQL or H2. Spring Boot simplifies the configuration and use of these technologies by providing default settings and auto-setup, making it easier to work with databases without delving deeply into complex configuration files.

Java Persistence API (JPA)

JPA is a specification that outlines how Java objects should be persisted in relational databases. It provides an abstraction over various ORM implementations like Hibernate and EclipseLink, handling the mapping of Java classes to database tables. This makes database operations more intuitive and aligned with object-oriented programming principles.

  • Entities: JPA entities are Java classes annotated with @Entity, representing database tables. Each entity instance corresponds to a row in the table.
  • Repositories: Spring Data JPA provides repository interfaces like JpaRepository, abstracting the data access layer and eliminating boilerplate code.

Hibernate ORM

Hibernate is a popular implementation of JPA that handles the conversion of Java objects to database records and vice versa. It manages:

  • Entity States: Entities can be transient, persistent, or detached depending on their lifecycle and persistence context.
  • Lazy and Eager Loading: Hibernate allows you to define how related entities are fetched—on-demand or upfront.
  • Caching: Hibernate provides caching mechanisms to improve performance by reducing the number of database hits.

Spring Data JPA

Spring Data JPA simplifies the development of JPA-based repositories by providing a repository abstraction over JPA. It allows you to perform common database operations (CRUD) without writing much code.

Features include:

  • CRUD Operations: Basic operations like save, delete, and find by ID are readily available.
  • Query Methods: Define query methods by following naming conventions. For example, findByName(String name) generates a query to find entities by the name field.
  • Custom Queries: Use JPQL (Java Persistence Query Language) or native SQL queries for complex queries.
  • Pagination and Sorting: Built-in support for pagination and sorting of results.

Database Integrations (MySQL and H2)

  • MySQL: A widely used relational database management system known for its reliability, performance, and ease of use. It is ideal for production environments where data needs to be persistently stored.
  • H2 Database: An in-memory database that is extremely fast and useful for development and testing. As it is in-memory, data is lost once the application is stopped. H2 provides excellent support and allows you to switch between databases with minimal configuration changes.

Steps to Integrate MySQL and H2 in a Spring Boot Application

Step 1: MySQL Integration

To integrate MySQL, typically used in production environments:

1. Add the Dependencies: Include spring-boot-starter-data-jpa and mysql-connector-java in your pom.xml.

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
    <groupId>com.mysql</groupId>
    <artifactId>mysql-connector-j</artifactId>
    <scope>runtime</scope>
</dependency>


2. Configure MySQL Connection: Update application.properties with MySQL database configuration.

spring.datasource.url=jdbc:mysql://localhost:3306/springbootdb
spring.datasource.username=root
spring.datasource.password=password
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL8Dialect

3. Database Initialization (Optional): Use schema.sql and data.sql files to initialize the database schema and data.

Step 2: H2 Database Integration

H2 is useful for development and testing:

1. Add the Dependencies: Include spring-boot-starter-data-jpa and h2 in your pom.xml.

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
    <groupId>com.h2database</groupId>
    <artifactId>h2</artifactId>
    <scope>runtime</scope>
</dependency>

2. Configure H2 Connection: Update application-dev.properties with H2 database configuration. Enable the H2 console for easy access to the in-memory database via the web interface.

spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=password
spring.jpa.hibernate.ddl-auto=update
spring.h2.console.enabled=true
spring.h2.console.path=/h2-console

3. Auto Schema Generation: H2 will automatically generate the schema based on JPA entities.

Switching Between Databases

Spring Boot makes it easy to switch between MySQL and H2 or other databases by changing the configuration in the application.properties file. This flexibility allows developers to use H2 for local development and MySQL in production without altering the codebase.

Implementation Example

Here’s a simple Spring Boot project demonstrating integration with MySQL and H2 databases using JPA and Hibernate.

Step 1: Create the New Spring Boot Project

Use your preferred IDE to create a new Spring Boot project with the following settings:

  • Name: spring-boot-database-integration
  • Language: Java
  • Type: Maven
  • Packaging: Jar

Click on the Next button.

Project Metadata

Step 2: Add the Dependencies

Add the following dependencies into the Spring Boot project.

Dependencies

Project Structure:

The project structure will look like this:

Project Folder Structure

Step 3: Configure Application Properties

Open application.properties and add the MySQL configuration. This file configures the connection details required to integrate MySQL with your Spring Boot application.

spring.application.name=spring-boot-database-integration

# MySQL Configuration
spring.datasource.url=jdbc:mysql://localhost:3306/testdb
spring.datasource.username=root
spring.datasource.password=mypassword
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL8Dialect

Step 4: Configure Application Dev Properties

Create application-dev.properties and add the H2 configuration. This file sets up the H2 in-memory database for development and testing purposes.

# H2 Database Configuration
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=password
spring.jpa.hibernate.ddl-auto=update
spring.h2.console.enabled=true
spring.h2.console.path=/h2-console

Step 5: Customer Entity

Customer is an entity class representing the Customer table in the database. It defines the fields, constructors, and getter/setter methods required for the entity.

Java
package com.gfg.springbootdatabaseintegration;

import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;

@Entity
public class Customer {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String firstName;
    private String lastName;
    private String email;

    // Constructors
    public Customer() {
    }

    public Customer(String firstName, String lastName, String email) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.email = email;
    }

    // Getters and Setters
    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }
}


Step 6: Customer Repository

CustomerRepository is a Spring Data JPA repository that provides CRUD operations for the Customer entity. It extends JpaRepository to inherit standard data access methods.

Java
package com.gfg.springbootdatabaseintegration;

import org.springframework.data.jpa.repository.JpaRepository;

public interface CustomerRepository extends JpaRepository<Customer, Long> {
}

Step 7: Customer Controller

CustomerController is a REST controller that handles HTTP requests for Customer entities. It provides endpoints for CRUD operations, allowing you to manage customers via RESTful services.

Java
package com.gfg.springbootdatabaseintegration;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

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

@RestController
@RequestMapping("/customers")
public class CustomerController {

    @Autowired
    private CustomerRepository customerRepository;

    @GetMapping
    public List<Customer> getAllCustomers() {
        return customerRepository.findAll();
    }

    @GetMapping("/{id}")
    public Customer getCustomerById(@PathVariable Long id) {
        Optional<Customer> customer = customerRepository.findById(id);
        return customer.orElse(null);
    }

    @PostMapping
    public Customer createCustomer(@RequestBody Customer customer) {
        return customerRepository.save(customer);
    }

    @PutMapping("/{id}")
    public Customer updateCustomer(@PathVariable Long id, @RequestBody Customer updatedCustomer) {
        Optional<Customer> customer = customerRepository.findById(id);
        if (customer.isPresent()) {
            Customer existingCustomer = customer.get();
            existingCustomer.setFirstName(updatedCustomer.getFirstName());
            existingCustomer.setLastName(updatedCustomer.getLastName());
            existingCustomer.setEmail(updatedCustomer.getEmail());
            return customerRepository.save(existingCustomer);
        }
        return null;
    }

    @DeleteMapping("/{id}")
    public void deleteCustomer(@PathVariable Long id) {
        customerRepository.deleteById(id);
    }
}

Step 8: Main Class

Java
package com.gfg.springbootdatabaseintegration;

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

@SpringBootApplication
public class SpringBootDatabaseIntegrationApplication {

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

}

pom.xml file:

XML
<?xml version="1.0" encoding="UTF-8"?>
<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.3.2</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.gfg</groupId>
    <artifactId>spring-boot-database-integration</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>spring-boot-database-integration</name>
    <description>spring-boot-database-integration</description>
    <url/>
    <licenses>
        <license/>
    </licenses>
    <developers>
        <developer/>
    </developers>
    <scm>
        <connection/>
        <developerConnection/>
        <tag/>
        <url/>
    </scm>
    <properties>
        <java.version>17</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>com.mysql</groupId>
            <artifactId>mysql-connector-j</artifactId>
            <scope>runtime</scope>
        </dependency>

        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <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>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

Step 10: Run the Application

Now, run the application and it will start at port 8080.

Application Runs

This project demonstrates the integration of the MySQL and H2 database of the Spring Boot project. If you observe the application logs of the project, it shows the database connections of the MySQL and H2 Databases of the Spring Boot application.


Next Article

Similar Reads