Connecting to a Database with Spring Boot

In this tutorial, we’ll explore how to connect a Spring Boot application to a database using Spring Data JPA. We’ll cover the following steps:

  1. Setting up the project dependencies
  2. Configuring the database connection
  3. Creating a data model
  4. Implementing a repository
  5. Performing database operations

Prerequisites

Before starting the tutorial, ensure you have the following prerequisites:

  1. Java Development Kit (JDK) installed on your machine.
  2. An Integrated Development Environment (IDE) such as IntelliJ IDEA or Eclipse.
  3. A database management system (e.g., MySQL, PostgreSQL) installed and running.

Step 1: Setting up the project dependencies

To begin, let’s set up a new Spring Boot project with the necessary dependencies:

  1. Open your preferred web browser and navigate to Spring Initializr.
  2. Set the following project details:
    • Project: Maven Project
    • Language: Java
    • Spring Boot: {Choose the latest stable version}
    • Group: com.example
    • Artifact: spring-boot-database
    • Packaging: Jar
    • Java: {Choose the Java version you have installed}
  3. Click on the "Add Dependencies" button and add the following dependencies:
    • Spring Web
    • Spring Data JPA
    • Database Driver (e.g., MySQL Connector, PostgreSQL Driver)
  4. Click the "Generate" button to download the project as a ZIP file.
  5. Extract the downloaded ZIP file to a directory of your choice.

Step 2: Configuring the database connection

Next, let’s configure the database connection settings in the Spring Boot application.

  1. Open the src/main/resources/application.properties file.

  2. Add the following configuration properties based on your database type and connection details:

    # Database configuration
    spring.datasource.url=jdbc:mysql://localhost:3306/mydatabase
    spring.datasource.username=db_username
    spring.datasource.password=db_password
    spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
    
    # Hibernate configuration
    spring.jpa.hibernate.ddl-auto=update
    spring.jpa.show-sql=true
    

    Replace mydatabase, db_username, and db_password with your actual database name, username, and password, respectively.

Step 3: Creating a data model

In this step, let’s create a simple data model that represents an entity in our database.

  1. Create a new Java class named Product under the com.example.demo package with the following content:

    package com.example.demo;
    
    import javax.persistence.Entity;
    import javax.persistence.GeneratedValue;
    import javax.persistence.GenerationType;
    import javax.persistence.Id;
    
    @Entity
    public class Product {
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        private Long id;
        private String name;
        private double price;
    
        // Constructors, getters, and setters
    }
    

    The @Entity annotation specifies that this class is an entity that will be mapped to a database table. The @Id annotation denotes the primary key, and the @GeneratedValue annotation configures the primary key generation strategy.

Step 4: Implementing a repository

In this step, let’s create a repository interface that will handle the database operations for the Product entity.

  1. Create a new Java interface named ProductRepository under the com.example.demo package with the following content:

    package com.example.demo;
    
    import org.springframework.data.jpa
    
    

.repository.JpaRepository;

public interface ProductRepository extends JpaRepository<Product, Long> { }


The `JpaRepository` interface provides the basic CRUD operations (Create, Read, Update, Delete) for our `Product` entity.

### Step 5: Performing database operations

Now that we have our data model and repository in place, let's perform some database operations in our Spring Boot application.

1. Create a new Java class named `DatabaseApplication` under the `com.example.demo` package with the following content:

```java
package com.example.demo;

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

import java.util.List;

@SpringBootApplication
public class DatabaseApplication {

    public static void main(String[] args) {
        ApplicationContext context = SpringApplication.run(DatabaseApplication.class, args);
        ProductRepository productRepository = context.getBean(ProductRepository.class);

        // Create a new product
        Product product = new Product();
        product.setName("Example Product");
        product.setPrice(9.99);
        productRepository.save(product);

        // Fetch all products
        List<Product> productList = productRepository.findAll();
        for (Product p : productList) {
            System.out.println("Product ID: " + p.getId() + ", Name: " + p.getName() + ", Price: " + p.getPrice());
        }
    }
}

In the main method, we obtain an instance of the ProductRepository using dependency injection. We then create a new Product entity, save it to the database using the repository, and fetch all products from the database.

Step 6: Build and run the application

  1. Open a terminal or command prompt and navigate to the project’s root directory.

  2. Build the application using the following command:

    mvn clean install
    
  3. Once the build completes successfully, run the application with the following command:

    java -jar target/spring-boot-database.jar
    

    Ensure that your database server is running before executing the command.

That’s it! You have successfully connected a Spring Boot application to a database using Spring Data JPA.

Feel free to explore more advanced database operations and configurations with Spring Data JPA. The official Spring Data JPA documentation provides detailed information on various features and customization options.

Happy coding!

Introduction to Spring Boot for Beginners

Leave a Reply

Shopping cart

0
image/svg+xml

No products in the cart.

Continue Shopping