IT기술/spring

[spring] postgre db JDBC 연결 테스트

미노드 2024. 1. 23. 11:54

부트 프로젝트를 만들고, local에 설치해둔 postgredb와 연결해보려 합니다.

프로젝트를 만들고 설정을 정리해두겠습니다..

1. JDBC 연결하기

저는 42.6.0버전을 사용하려 합니다.

2. 프로퍼티에 정보 등록

# Postgresql
spring.datasource.url=jdbc:postgresql://localhost:5432/ticket
spring.datasource.username=userid
spring.datasource.password=password

# JPA
spring.jpa.hibernate.dialect = org.hibernate.dialect.PostgreSQL10Dialect
spring.jpa.hibernate.ddl-auto=update
spring.jpa.properties.hibernate.format_sql = true
spring.jpa.show-sql = true

3. postgre 샘플 데이터베이스 작성

postgre 데이터베이스를 새로 만들고 계정을 생성 했습니다.에 샘플 데이터를 작성했습니다.

4. 테스트 진행.

프로젝트에 연결 테스트를 진행해봤습니다.

package com.dominod.bootproject.service;

import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

@SpringBootTest
public class PostgreConLocalTests {
    // DB Driver
    String dbDriver = "org.postgresql.Driver";

    // DB URL
    // IP:PORT/스키마
    String dbUrl = "jdbc:postgresql://localhost:5432/ticket";

    // DB ID/PW
    String dbUser = "userid";
    String dbPassword = "userpw";

    @Test
    public void dbConnection()
    {
        Connection conn = null;

        try
        {
            Class.forName(dbDriver); //JDBC 드라이버 이름으로 드라이버를 로드함.
//            conn=DriverManager.getConnection(url,"아이디 자리","비밀번호 자리");
            conn = DriverManager.getConnection(dbUrl, dbUser, dbPassword);

            System.out.println("DB Connection [성공]");
            conn.close();	//데이터베이스와의 연결을 해제함
        }
        catch (SQLException e)
        {
            e.printStackTrace();
        }
        catch (ClassNotFoundException e)
        {
            e.printStackTrace();
        }
    }
}

테스트를 수행했는데, 아래처럼 에러가 발생했습니다.
왜그런지 확인해봤는데, 그래들에서 jdbc를 추가 후 refresh를 안해줘서 그런것이었네요.

Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.zaxxer.hikari.HikariDataSource]: Factory method 'dataSource' threw exception with message: Failed to load driver class org.postgresql.Driver in either of HikariConfig class loader or Thread context classloader
	at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:177)
	at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:647)

새로고침 후 다시 실행해보면, 연결이 정상적으로 되는 것을 확인할 수 있습니다.