How to Connect Your Spring Boot App to MySQL or PostgreSQL

Here’s a guide on how to connect your Spring Boot application to a MySQL or PostgreSQL database. These steps assume you are already familiar with basic Spring Boot concepts.

1. Add the Necessary Dependencies

Open your (for Maven) or build.gradle (for Gradle), and add the database driver and Spring Boot starter dependencies: pom.xml
Maven:

<!-- MySQL Driver -->
<dependency>
    <groupId>com.mysql</groupId>
    <artifactId>mysql-connector-j</artifactId>
    <scope>runtime</scope>
</dependency>

<!-- PostgreSQL Driver -->
<dependency>
    <groupId>org.postgresql</groupId>
    <artifactId>postgresql</artifactId>
    <scope>runtime</scope>
</dependency>

<!-- Spring Data JPA -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

2. Configure application.yml or application.properties

Set up the database connection details based on the database you’re using. Here’s an example configuration for both MySQL and PostgreSQL:

For MySQL:

application.properties:

spring.datasource.url=jdbc:mysql://localhost:3306/your_database_name
spring.datasource.username=your_username
spring.datasource.password=your_password
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

# JPA Properties (Optional, but recommended)
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL8Dialect
spring.jpa.hibernate.ddl-auto=update

application.yml:

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/your_database_name
    username: your_username
    password: your_password
    driver-class-name: com.mysql.cj.jdbc.Driver

  jpa:
    properties:
      hibernate:
        dialect: org.hibernate.dialect.MySQL8Dialect
    hibernate:
      ddl-auto: update

For PostgreSQL:

application.properties:

spring.datasource.url=jdbc:postgresql://localhost:5432/your_database_name
spring.datasource.username=your_username
spring.datasource.password=your_password
spring.datasource.driver-class-name=org.postgresql.Driver

# JPA Properties (Optional, but recommended)
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect
spring.jpa.hibernate.ddl-auto=update

application.yml:

spring:
  datasource:
    url: jdbc:postgresql://localhost:5432/your_database_name
    username: your_username
    password: your_password
    driver-class-name: org.postgresql.Driver

  jpa:
    properties:
      hibernate:
        dialect: org.hibernate.dialect.PostgreSQLDialect
    hibernate:
      ddl-auto: update

Important Notes:

  • Replace your_database_name, your_username, and your_password with your actual database details.
  • spring.jpa.hibernate.ddl-auto=update ensures automatic table creation based on your entity classes but should not be used in production.

3. Create a JPA Entity and Repository

Define a sample entity and repository to test the database connection.
Entity Example:

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

@Entity
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String name;
    private String email;

    // Getters and Setters
}

Repository Example:

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

public interface UserRepository extends JpaRepository<User, Long> {
}

4. Test the Connection

Create a test controller or service to interact with the UserRepository and validate the connection.
Example RestController:

import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/users")
public class UserController {

    private final UserRepository userRepository;

    public UserController(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    @PostMapping
    public User createUser(@RequestBody User user) {
        return userRepository.save(user);
    }

    @GetMapping
    public List<User> getAllUsers() {
        return userRepository.findAll();
    }
}

5. Run the Application

Start your Spring Boot application, and it should connect to the configured database. You can debug or use a tool like Postman to test the defined endpoints.

6. (Optional) Use Flyway or Liquibase for Database Migrations

For better database version control, it’s advisable to use Flyway or Liquibase instead of relying on spring.jpa.hibernate.ddl-auto. This ensures better management of your database schema in production environments.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.