티스토리 뷰

스프링 로고
PostgreSQL 로고

 

 

개발 환경

 

Spring Boot 3.1.8
JAVA 17
PostgreSQL 16.1
Docker 24.0.7

 

 

 

 

 

 

사전 준비

 

도커로 PostgreSQL 서버를 띄우고 동작해야지 Spring과 PostgreSQL을 연동할 수 있습니다.

이전 글인 [개발환경] MacOS 도커로 PostgreSQL DB 실행하기 을 보고 오면 아래와 같은 환경설정이 됩니다.

 

  • Database : postgres
  • Username : postgres
  • password : 0000

 

 

 

 

 

 

내가 만난 에러 목록들

 

제가 적용하면서 만났던 오류들 입니다.  본 글을 읽을라면 아래로 내려가주시고

같은 오류가 발생하면 다시올라와 해당 오류의 글을 읽고 처리해 주시면 됩니다.

 

 

에러a.  (PSQLException) FATAL: password authentication failed for user "postgres"

이 오류는 데이터 베이스에 연결하려는데 비밀번호가 올바르지 않거나, 데이터 베이스 서버에 비밀번호 인증을 수행하지 못했을 때 발생합니다.

 

에러a. 해결 방안 1번 : 비밀번호 문자열로 변경

더보기
<!-- 에러 버전 -->
spring:
  datasource:
    url:  jdbc:postgresql://localhost:5432/postgres
    username: postgres
    password: 0000
    driver-class-name: org.postgresql.Driver
    
<!-- 해결 방법 : username과 password 문자열로 변경 -->
spring:
  datasource:
    url:  jdbc:postgresql://localhost:5432/postgres
    username: "postgres"
    password: "0000"
    driver-class-name: org.postgresql.Driver

에러a. 해결 방안 2번 : PostgreSQL 데이터 베이스 서버에서 pg_hga.conf 파일에서 권한 확인

더보기

pg_hga.conf 파일에 들어가보면 인증 메커니즘과 접근 권한을 확인하면 됩니다. 

아래와 같으면 됩니다.

pg_hga.conf 파일 내용

 

 

 

에러b.  DB 스키마를 내가 원하는대로 접근이 안될어 null 값 나올 때

기본적으로 스키마가 public 으로 생성되어 있다. 하지만 나는 spring이라는 스키마를 만들어 데이터를 넣어 주었다.

그런데 테스트 코드를 작성하고 실행을 돌려보니 public 스키마를 타고있었고, null 값이 나오는 것이였다.

 

에러b. 해결 방안 1번 : 테스트 코드 DB 연결 URL에 스키마 작성

더보기

jdbc:postgresql://localhost:5432/postgres 이렇게 DB 연결 URL을 작성하고 뒤에
?currentSchema=spring 나의 스키마 명으로 파라미터를 붙이게 되었다.

public class PostgreSQLConnectionTest {

    private String URL = "jdbc:postgresql://localhost:5432/postgres?currentSchema=spring";
    private String USERNAME = "postgres";
    private String PASSWORD = "0000";

    @Test
    @DisplayName("DB 연결 및 특정 ID의 이름 검증")
    public void ConnectionNamePrintTest() throws Exception {
        
        // ~~ 테스트 코드 생략~
        // 아래에서 코드 보여줄 예정
    }
}

 

 

 

 

 

 

 

 

코드

 

build.gradle

plugins {
	id 'java'
	id 'org.springframework.boot' version '3.1.8'
	id 'io.spring.dependency-management' version '1.1.4'
}

group = 'com.aoxx'
version = '0.0.1-SNAPSHOT'

java {
	sourceCompatibility = '17'
}

configurations {
	compileOnly {
		extendsFrom annotationProcessor
	}
}

repositories {
	mavenCentral()
}

dependencies {
	implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
	implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
	implementation 'org.springframework.boot:spring-boot-starter-web'
	implementation group: 'org.postgresql', name: 'postgresql', version: '42.7.1'
	compileOnly 'org.projectlombok:lombok'
	developmentOnly 'org.springframework.boot:spring-boot-devtools'
	annotationProcessor 'org.projectlombok:lombok'
	testImplementation 'org.springframework.boot:spring-boot-starter-test'
}

tasks.named('bootBuildImage') {
	builder = 'paketobuildpacks/builder-jammy-base:latest'
}

tasks.named('test') {
	useJUnitPlatform()
}

 

application.yml

# ===============================
# Server Property
# ===============================

spring:
  datasource:
    url:  jdbc:postgresql://localhost:5432/postgres
    username: "postgres"
    password: "0000"
    driver-class-name: org.postgresql.Driver
  jpa:
    show-sql: true
    database: postgresql
    hibernate:
      ddl-auto: update

 

 

 

 

 

 

DB 연결 테스트코드와 서버 기동

 

테스트 코드

import org.assertj.core.api.Assertions;
import org.assertj.core.api.Fail;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;

import java.sql.*;

public class PostgreSQLConnectionTest {

    private String URL = "jdbc:postgresql://localhost:5432/postgres?currentSchema=spring";
    private String USERNAME = "postgres";
    private String PASSWORD = "0000";


    @Test
    @DisplayName("DB 연결테스트")
    public void ConnectionTest() throws Exception{
        Connection con = DriverManager.getConnection(URL,USERNAME,PASSWORD); //db 연결
        Assertions.assertThat(con).isNotNull();
    }

    @Test
    @DisplayName("DB 연결 및 특정 ID의 이름 검증")
    public void ConnectionNamePrintTest() throws Exception {
        // Given
        try (Connection con = DriverManager.getConnection(URL, USERNAME, PASSWORD);
             Statement pre = con.createStatement();
             // DB 스키마 이름이 spring , 테이블 명 : members.info
             ResultSet rs = pre.executeQuery("SELECT * FROM members_info WHERE id = 9")) {

            // When
            String name = null;
            if (rs.next()) {
                name = rs.getString("name");
            }

            // Then
            Assertions.assertThat(name).isEqualTo("Illaoi Quirinus Quirrell");
        } catch (SQLException e) {
            // 예외 처리
            Fail.fail("테스트에 예외가 발생했습니다: " + e.getMessage());
        }
    }
}

테스트 코드 실행
테스트 코드 성공 여부

 

DB 데이터 내용
DB 에 들어있는 ID = 9 번인 멤버 이름

 

 

 

서버 기동

서버 기동하여 나온index.html

 

 

 

감사합니다.

공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/04   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30
글 보관함