[JAVA] Spring Boot와 PostgreSQL 연동하기 – 실전 가이드

Spring Boot에서 PostgreSQL과 연동하는 것은 대규모 서비스나 오픈소스 기반 프로젝트에서 자주 사용되는 설정입니다.
초보자도 쉽게 따라할 수 있는 PostgreSQL 연동 방법을 단계별로 알려드리겠습니다.

 


1. PostgreSQL 설치 및 설정

먼저 로컬 또는 Docker에 PostgreSQL을 설치합니다.

# macOS (Homebrew)
brew install postgresql
brew services start postgresql
psql postgres

# 기본 계정으로 비밀번호 설정
\password postgres

Docker를 사용할 경우 다음 명령어로 실행할 수 있습니다.

docker run --name postgres-spring \
  -e POSTGRES_PASSWORD=1234 \
  -e POSTGRES_DB=springboot_db \
  -p 5432:5432 \
  -d postgres:15

 

2. 데이터베이스 생성

애플리케이션에서 사용할 데이터베이스를 생성합니다.

CREATE DATABASE springboot_db;

 

3. 의존성 추가 (Maven 기준)

Spring Boot 프로젝트의 pom.xml 파일에 PostgreSQL 및 JPA 의존성을 추가합니다.


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

<dependency>
  <groupId>org.postgresql</groupId>
  <artifactId>postgresql</artifactId>
</dependency>

 

4. application.yml 설정

PostgreSQL 연결 정보를 설정 파일에 입력합니다.

# src/main/resources/application.yml
spring:
  datasource:
    url: jdbc:postgresql://localhost:5432/springboot_db
    username: postgres
    password: 1234
    driver-class-name: org.postgresql.Driver

  jpa:
    hibernate:
      ddl-auto: update
    show-sql: true
    properties:
      hibernate:
        format_sql: true

application.properties로 구성할 경우 아래와 같이 작성합니다.

spring.datasource.url=jdbc:postgresql://localhost:5432/springboot_db
spring.datasource.username=postgres
spring.datasource.password=1234
spring.datasource.driver-class-name=org.postgresql.Driver

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

 

5. Entity, Repository 작성 예시

간단한 유저 엔티티를 만들어 연동 테스트를 해봅니다.

@Entity
public class User {
    @Id @GeneratedValue
    private Long id;

    private String name;
    private String email;
}
public interface UserRepository extends JpaRepository<User, Long> {
    Optional<User> findByEmail(String email);
}

 

6. 실행 및 동작 확인

Spring Boot 프로젝트를 실행하면 PostgreSQL에 연결되어 테이블이 자동 생성됩니다.
SQL 로그도 함께 출력되므로 정상 동작을 쉽게 확인할 수 있습니다.

 

7. 자주 발생하는 오류와 해결 방법

  • org.postgresql.Driver not found: 의존성 누락 여부 확인
  • Connection refused: PostgreSQL이 실행 중인지, 포트가 맞는지 확인
  • Timezone 문제: PostgreSQL은 JDBC URL에 timezone 설정이 필요하지 않음
  • Access denied: PostgreSQL 계정 비밀번호 및 권한 설정 확인

 

마무리

PostgreSQL은 신뢰성과 확장성이 뛰어나 많은 대형 프로젝트에서 사용되고 있습니다.
Spring Boot와 PostgreSQL 연동의 핵심 흐름을 익혔다면, 이제 JPA, QueryDSL, 트랜잭션 설정까지 확장해 보시는 것을 추천합니다.