스프링 부트에 PostgreSQL 로컬 db 연동하기

YulHee Kim·2021년 10월 4일
0

의존성 추가

implementation group: 'org.postgresql', name: 'postgresql'

version 정보를 지정해주지 않으면 스프링부트가 알아서 최적화된 버전으로 지정해준다고 한다.

설정 파일

spring:
  datasource:
    url: jdbc:postgresql://localhost:5432/db명
    username: sloth
    password: 비밀번호
    driver-class-name: org.postgresql.Driver

postgresql은 기본 포트가 5432이다.

test 코드

example/PostgreSQLRunner

@Component
public class PostgresSQLRunner implements ApplicationRunner {
    @Autowired
    DataSource dataSource;

    @Autowired
    JdbcTemplate jdbcTemplate;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        try (Connection connection = dataSource.getConnection()){
            System.out.println(dataSource.getClass());
            System.out.println(connection.getMetaData().getURL());
            System.out.println(connection.getMetaData().getUserName());

            Statement statement = connection.createStatement();
            String sql = "CREATE TABLE t_product(product_no INTEGER NOT NULL, product_name VARCHAR(255), PRIMARY KEY (product_no))";
            statement.executeUpdate(sql);
        }
        jdbcTemplate.execute("INSERT INTO t_product VALUES (1, 'Big shirt')");
    }
}

콘솔에 디비 정보가 뜬다

jdbc:postgresql://localhost:5432/slothdb
sloth

DB 확인

로컬 디비에 연동됐다.
다음은 도커 컨테이너도 이용해보겠다

profile
백엔드 개발자

0개의 댓글