스프링 부트, 입문!

스프링 부트, 입문!

쉽고 빠르게 배우는, 스프링 부트 첫걸음!

28 DB 연동하기

# DB 연동하기 ## 미션 PostgreSQL을 설치하고, 이를 스프링 부트와 연동하시오. ![홍팍-스프링-부트-입문-DB-연동-미션](http://drive.google.com/uc?export=view&id=1eKr4o6g6Wjc2IINpLJDq2UQWM-Gp7EJi) ## 07:15 DB 드라이버 추가 - build.gradle, start.spring.io #### firstproject/build.gradle ``` plugins { id 'org.springframework.boot' version '2.6.6' // 스프링 부트 버전 id 'io.spring.dependency-management' version '1.0.11.RELEASE' id 'java' } group = 'com.example' version = '0.0.1-SNAPSHOT' sourceCompatibility = '17' // JDK 버전 repositories { mavenCentral() } dependencies { // 28강: PostgreSQL 드라이버 추가! runtimeOnly 'org.postgresql:postgresql' // 10강: 롬복 추가 compileOnly 'org.projectlombok:lombok' annotationProcessor 'org.projectlombok:lombok' implementation 'org.springframework.boot:spring-boot-starter-data-jpa' implementation 'org.springframework.boot:spring-boot-starter-mustache' implementation 'org.springframework.boot:spring-boot-starter-web' runtimeOnly 'com.h2database:h2' testImplementation 'org.springframework.boot:spring-boot-starter-test' } test { useJUnitPlatform() } ``` ## 09:10 DB 연동 설정 - application.properties #### ../resources/application.properties ``` # 09강: h2 DB, 웹 콘솔 설정 spring.h2.console.enabled=true # 15강: data.sql 적용을 위한 설정(스프링부트 2.5 이상) spring.jpa.defer-datasource-initialization=true # 17강: JPA 로깅 설정 ## 디버그 레벨로 쿼리 출력 logging.level.org.hibernate.SQL=DEBUG ## 이쁘게 보여주기 spring.jpa.properties.hibernate.format_sql=true ## 파라미터 보여주기 logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE ## 고정 url 설정 #spring.datasource.url=jdbc:h2:mem:testdb # 28강: PostgreSQL 연동 spring.datasource.url=jdbc:postgresql://localhost:5432/firstproject_db spring.datasource.username=postgres spring.datasource.password=postgres spring.datasource.data=classpath:/data.sql spring.datasource.initialization-mode=always spring.jpa.hibernate.ddl-auto=create-drop ``` ## 11:46 DB 데이터 유지하기 - initialization-mode, ddl-auto #### ../resources/application.properties ``` ... # 28강: PostgreSQL 연동 spring.datasource.url=jdbc:postgresql://localhost:5432/firstproject_db spring.datasource.username=postgres spring.datasource.password=postgres spring.datasource.data=classpath:/data.sql spring.datasource.initialization-mode=never spring.jpa.hibernate.ddl-auto=update ``` ## 13:11 DB로 직접 데이터 확인 - pgAdmin #### SQL 쿼리 직접 다루기 ``` -- 게시글 조회 SELECT * FROM article ; -- 댓글 조회 SELECT * FROM comment ; ``` ## 🔥 구글링 훈련하기 - PostgreSQL 장점 - JPA 초기화 전략 - JPA ddl-auto 설정 - pgAdmin 사용법 - JPA 방언 설정