Developer/Spring

Spring boot와 PostgreSQL 연결하기

또쟁이 2025. 6. 3. 20:00

Spring boot 와 PostgreSQL 을 연결해보려 한다

PostgreSQL 드라이버 추가

# build.gradle 파일 수정
runtimeOnly 'org.postgresql:postgresql'

properties에 PostgreSQL 연결 설정을 추가한다

# application.properties 파일 수정
# PostgreSQL Database Configuration
spring.datasource.url=jdbc:postgresql://localhost:5432/[Database명]
spring.datasource.username=[username]
spring.datasource.password=[password]
spring.datasource.driver-class-name=org.postgresql.Driver

# JPA/Hibernate Configuration
spring.jpa.hibernate.ddl-auto=create-drop
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true
spring.jpa.database-platform=org.hibernate.dialect.PostgreSQLDialect

로컬 PostgreSQL 설치 확인 (일단 로컬 DB 로 연결하려 함)

which psql /opt/homebrew/bin/psql

PostgreSQL 서비스 실행 확인

brew services list | grep postgresql

postgresql@14 none 결과라면, 설치는 되어있지만, 실행되지 않은 상태임

# PostgreSQL 실행
brew services start postgresql@14

PostgreSQL 실행 후, DB 에 접속할 계정 생성 및 데이터베이스 생성해야함

  • 유저 정보를 새로 생성하거나 수정했다면, properties 파일도 수정
    # 데이터베이스 존재 여부 확인
    psql -U [user_name] -d postgres -c "\l"

Entity 테스트

# TestEntity.java 파일 추가

import jakarta.persistence.*;
import lombok.Data;

@Entity
@Table(name = "test_table")
@Data
public class TestEntity {

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

    @Column(nullable = false)
    private String name;

    @Column
    private String description;
}
# TestRpository.java 파일 추가

import com.sunwise.fredgeverse_be.entity.TestEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface TestRepository extends JpaRepository<TestEntity, Long> {
}
# HelloController.java 파일 수정

import com.sunwise.fredgeverse_be.entity.TestEntity;
import com.sunwise.fredgeverse_be.repository.TestRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
public class HelloController {

    @Autowired
    private TestRepository testRepository;

    @GetMapping("/hello")
    public String hello() {
        return "Hello! 서버가 정상적으로 작동하고 있습니다! 🚀";
    }

    @GetMapping("/health")
    public String health() {
        return "OK - Server is running!";
    }

    @GetMapping("/db-test")
    public String dbTest() {
        try {
            // 테스트 데이터 생성
            TestEntity testEntity = new TestEntity();
            testEntity.setName("테스트 데이터");
            testEntity.setDescription("PostgreSQL 연결 테스트");

            // 데이터베이스에 저장
            testRepository.save(testEntity);

            // 저장된 데이터 조회
            List<TestEntity> allData = testRepository.findAll();

            return "✅ 데이터베이스 연결 성공! 저장된 데이터 수: " + allData.size();
        } catch (Exception e) {
            return "❌ 데이터베이스 연결 실패: " + e.getMessage();
        }
    }
} 

서비스 중지 후 재시작

pkill -f "fredgeverse"
./gradlew bootRun

연결 성공 확인