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:
- Setting up the project dependencies
- Configuring the database connection
- Creating a data model
- Implementing a repository
- Performing database operations
Prerequisites
Before starting the tutorial, ensure you have the following prerequisites:
- Java Development Kit (JDK) installed on your machine.
- An Integrated Development Environment (IDE) such as IntelliJ IDEA or Eclipse.
- 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:
- Open your preferred web browser and navigate to Spring Initializr.
- 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}
- Click on the "Add Dependencies" button and add the following dependencies:
- Spring Web
- Spring Data JPA
- Database Driver (e.g., MySQL Connector, PostgreSQL Driver)
- Click the "Generate" button to download the project as a ZIP file.
- 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.
-
Open the
src/main/resources/application.properties
file. -
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
, anddb_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.
-
Create a new Java class named
Product
under thecom.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.
-
Create a new Java interface named
ProductRepository
under thecom.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
-
Open a terminal or command prompt and navigate to the project’s root directory.
-
Build the application using the following command:
mvn clean install
-
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!