Introduction
Database connectivity is a core requirement for many applications, and Spring Boot simplifies the process of integrating your application with databases. In this guide, we'll explore how to establish database connectivity in a Spring Boot application using sample code and examples.
Prerequisites
Before you start, make sure you have the following prerequisites:
- A Spring Boot project (if you don't have one, follow the "Building a Spring Boot Web Application" tutorial)
- An Integrated Development Environment (IDE) like Spring Tool Suite, IntelliJ IDEA, or Visual Studio Code
- A database system (e.g., MySQL, PostgreSQL, H2) installed and running
Adding Database Dependencies
To connect to a database in your Spring Boot project, you need to include the appropriate database driver dependency. If you're using MySQL, add the following dependency to your pom.xml
:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
</dependencies>
Make sure to replace "mysql" with the appropriate database driver if you're using a different database system.
Configuring Database Connection
Spring Boot uses a configuration file (usually application.properties
or application.yml
) to set up the database connection. Here's an example configuration for MySQL:
# application.properties
spring.datasource.url=jdbc:mysql://localhost:3306/mydb
spring.datasource.username=root
spring.datasource.password=secret
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.hibernate.ddl-auto=update
This configuration sets the database URL, username, password, and specifies the JDBC driver class. The spring.jpa.hibernate.ddl-auto
property is set to "update" to automatically update the schema based on the entity classes.
Creating an Entity
You need to create a JPA entity that represents a table in your database. Here's a simple example:
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String firstName;
private String lastName; // Getters and setters
}
This entity represents an "Employee" table with columns for ID, first name, and last name. The @Id
annotation marks the primary key.
Creating a Repository
You'll need a repository interface to perform database operations. Spring Data JPA provides a convenient way to create repositories. Here's an example:
import org.springframework.data.jpa.repository.JpaRepository;
public interface EmployeeRepository extends JpaRepository<Employee, Long> {
}
This repository extends JpaRepository
and is parametrized with the entity type ("Employee") and the primary key type ("Long"). This provides CRUD operations for the "Employee" entity.
Using the Repository
With the repository in place, you can use it to interact with the database in your service or controller classes. Here's an example of using the repository in a service class:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class EmployeeService {
private final EmployeeRepository employeeRepository;
@Autowired
public EmployeeService(EmployeeRepository employeeRepository) {
this.employeeRepository = employeeRepository;
}
public List<Employee> getAllEmployees() {
return employeeRepository.findAll();
}
// Other service methods
}
The @Autowired
annotation injects the repository into the service. The service can then use the repository methods to fetch and manipulate data.
Conclusion
Spring Boot simplifies database connectivity by providing easy-to-use tools and conventions. This guide covered adding database dependencies, configuring the database connection, creating an entity, repository, and using the repository to interact with the database. With these fundamentals, you can build data-driven applications using Spring Boot.