# DB를 H2에서 Postgresql로 변경해보자.
1. Postgresql DB 설치 및 연동은 아래의 URL에서 확인 후 설정한다.
2022.04.11 - [⭐ SpringBoot/𝄜 게시판 with SpringBoot] - 27. DB 설치 및 연동
27. DB 설치 및 연동
# PostgreSQL을 설치하고, 이를 스프링 부트와 연동한다. # 여기서는 PostgreSQL을 기반으로 연동을 하지만, 다른 SQL 프로그램들도 비슷한 흐름으로 연동하면 된다. DB 연동과정 1. DBMS를 설치 (PostgreSQL) 2
may9noy.tistory.com
2. build.gradle 파일에 Postgresql 라이브러리 추가
// PostgreSQL 라이브러리 추가
runtimeOnly 'org.postgresql:postgresql'
3. application.properties에 DB 접속정보 추가
#PostgreSQL - info
#spring.datasource.url=jdbc:postgresql://localhost:5432/postgres
spring.datasource.url=jdbc:postgresql://localhost:5432/test_db
spring.datasource.username=postgres
spring.datasource.password=test1234
# // create 끝난뒤 update로 설정 해주어야 한다.
spring.jpa.hibernate.ddl-auto=update
# // DB를 변경하거나 신규 생성시 최초는 create 이다.
#spring.jpa.hibernate.ddl-auto=create
spring.jpa.show_sql=true
spring.datasource.sql-script-encoding=utf-8
spring.main.allow-bean-definition-overriding=true
spring.jpa.properties.hibernate.format_sql = true
logging.level.org.hibernate.SQL=DEBUG
logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE
4. 신규 DB를 생성하거나 DB를 변경 후 Postgresql과 연동하기
- 일단 DB를 신규로 생성 후 SprinbBoot와 연동하려면 pgadmin과 같은 Client 툴이나 CLI 명령어를 통해 신규 DB를 생성해 줘야 한다.
- 간단하게 pgadmin의 예를 들면 아래와 같다.
test_02라는 DB를 생성한다.

application.properties 정보를 수정한다. 아래와 같이 DB 명만 변경한다.
그리고 ddl-auto 옵션을 create로 변경한다.
...
spring.datasource.url=jdbc:postgresql://localhost:5432/test_02
...
spring.jpa.hibernate.ddl-auto=create
...
프로그램을 시작한다. 그리고 pgadmin으로 이동하여 DB를 확인해보자.
ddl-auto 옵션을 create로 했기 때문에 해당 프로그램이 가지고 있는 entity 정보를 기반으로 테이블을 생성할 것이다.
확인해 보면 아래와 같다. 정상적으로 생성이 되었다.

이제 application.properties 에서 ddl-auto 옵션을 update로 수정한 뒤 프로그램을 재 시작한다.
그러면 테이블을 신규로 생성하거나 삭제하지 않고, 현재의 테이블 구조를 기반으로 추가되는 내용만 업데이트를 하게 된다.

- 여기까지 SpringBoot와 Postgresql을 연동하는 방법이다.
다음에는 Mybatis를 적용하는 과정을 해봐야 겠다.
- 끝 -
'🌱JAVA > 시나리오 개발' 카테고리의 다른 글
<SpringBoot> 로그인 및 회원가입 구현 (0) | 2023.05.03 |
---|---|
<SpringBoot> 게시판에 검색 기능 구현하기 (0) | 2023.04.28 |
<SpringBoot> Swagger 적용해보기 (0) | 2023.04.27 |
<SpringBoot> insert2개 수행, 1개는 그냥 insert, 1개는 Admin 붙여서 insert (0) | 2023.04.27 |
<SpringBoot> 댓글이 있는 게시글 삭제 시 오류 메세지 출력 및 게시글 삭제하기 (0) | 2023.04.27 |