How do I connect Spring to a database?

To connect Spring to a database, the usual modern approach is:

  1. Add database-related dependencies.
  2. Configure the database connection properties.
  3. Create an entity.
  4. Create a repository.
  5. Use the repository from a service or controller.

The simplest way is with Spring Boot + Spring Data JPA.


1. Add Maven Dependencies

For a Spring Boot application using JPA, add:

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

    <!-- Example: PostgreSQL driver -->
    <dependency>
        <groupId>org.postgresql</groupId>
        <artifactId>postgresql</artifactId>
        <scope>runtime</scope>
    </dependency>
</dependencies>

For MySQL instead:

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

If you are also building REST endpoints, you usually include:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

2. Configure application.properties

Create or update:

src/main/resources/application.properties

Example for PostgreSQL:

spring.datasource.url=jdbc:postgresql://localhost:5432/app
spring.datasource.username=postgres
spring.datasource.password=postgres

spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true

Example for MySQL:

spring.datasource.url=jdbc:mysql://localhost:3306/app
spring.datasource.username=root
spring.datasource.password=secret

spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true

Spring Boot will automatically create a DataSource, configure Hibernate, and connect Spring Data JPA to the database.


3. Create an Entity

Example:

package com.example.app.user;

import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import lombok.Getter;
import lombok.Setter;

@Entity
@Getter
@Setter
public class User {

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

    private String name;

    private String email;
}

The @Entity annotation tells JPA that this class maps to a database table.


4. Create a Repository

package com.example.app.user;

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

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

This gives you built-in methods such as:

findAll()
findById(id)
save(entity)
deleteById(id)

You do not need to manually open JDBC connections for common CRUD operations.


5. Use the Repository in a Service

package com.example.app.user;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class UserService {

    private final UserRepository userRepository;

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

    @Transactional(readOnly = true)
    public List<User> findAll() {
        return userRepository.findAll();
    }

    @Transactional
    public User save(User user) {
        return userRepository.save(user);
    }
}

Use @Transactional for methods that interact with the database.


6. Optional REST Controller Example

package com.example.app.user;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
public class UserController {

    private final UserService userService;

    public UserController(UserService userService) {
        this.userService = userService;
    }

    @GetMapping("/users")
    public List<User> users() {
        return userService.findAll();
    }
}

When you visit:

http://localhost:8080/users

Spring will query the database through the repository and return the users as JSON.


7. Recommended ddl-auto Values

The property:

spring.jpa.hibernate.ddl-auto=update

controls how Hibernate manages tables.

Common values:

Value Meaning
none Do not change the schema
validate Check that tables match entities
update Update tables automatically
create Drop and recreate tables on startup
create-drop Create on startup, drop on shutdown

For learning, update is convenient.

For production, prefer:

spring.jpa.hibernate.ddl-auto=validate

and use a migration tool such as Flyway or Liquibase.


8. Typical Spring Database Flow

Controller
    ↓
Service
    ↓
Repository
    ↓
Spring Data JPA / Hibernate
    ↓
DataSource
    ↓
Database

Quick Checklist

To connect Spring to a database:

  1. Add spring-boot-starter-data-jpa.
  2. Add the database driver, such as PostgreSQL or MySQL.
  3. Configure spring.datasource.url, username, and password.
  4. Create an @Entity.
  5. Create a JpaRepository.
  6. Inject the repository into a service.
  7. Use @Transactional for database operations.

For most Spring applications, you should let Spring Boot configure the DataSource automatically instead of manually creating JDBC connections.

Leave a Reply

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