INFLEARN/스프링 입문 - 코드로 배우는 스프링 부트

[스프링입문] 6. 스프링 DB 접근 기술

0298 2022. 6. 13. 23:48

6. 스프링 DB 접근 기술

 

[강의 정리] 김영한님 :: 스프링 입문 - 코드로 배우는 스프링 부트, 웹 MVC, DB 접근 기술

 

 

 

1. H2 데이터베이스 설치

 

# H2 데이터베이스

 

H2 Database Engine (redirect)

H2 Database Engine Welcome to H2, the free SQL database. The main feature of H2 are: It is free to use for everybody, source code is included Written in Java, but also available as native executable JDBC and (partial) ODBC API Embedded and client/server mo

h2database.com

  • h2 데이터베이스 버젼은 스프링 부트 벼젼에 맞춤

 

2. 순수 JDBC

고대방법....

# 환경설정

  • build.gradle jdbc, h2 관련 라이브러리 추가
implementation 'org.springframework.boot:spring-boot-starter-jdbc
runtimeOnly 'com.h2database:h2' // client
  • resources/application.properties 스프링 부트 데이터베이스 연결 설장 추가 
spring.datasource.url=jdbc:h2:tcp://localhost/~/test
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.username=sa // 스프링부트 2.4부터는 꼭 추가해야함

 

3. 스프링 통합 테스트

# 통합 테스트

  • @SpringBootTest
    • 스프링 컨테이너와 테스트를 함께 실행
  • @Transactional
    • 테스트 케이스에 이 애노테이션이 있으면, 테스트 시작 전에 트랜잭션을 시작하고, 테스트 완 후에 항상 롤백
    • DB에 데이터가 남지 않으므로 다음 테스트에 영향을 주지 않음

 

4. 스프링 JdbcTemplate

# JdbcTemplate

  • 순수 Jdbc와 동일한 환경설정을 하면 됨
  • 스프링 JdbcTemplate과 MyBatis 같은 라이브러리는 JDBC API에서 본 반복 코드를 대부분 제거해주지만 SQL은 작성해야함

 

5. JPA

# JPA

  • 기존 반복 코드 및 기본적인 SQL은 JPA가 직접 만들어서 실행 
  • 개발 생산성 증가
  • SQL과 데이터 중심 -> 객체 중심 설계로 패러다임을 전환

 

# 환경설정

  • build.gradle에 JPA, h2 관련 라이브러리 추가
    • spring-boot-starter-data-jpa는 내부에 jdbc 관련 라이브러리 포함
implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
implementation 'org.springframework.boot:spring-boot-starter-web'
// implementation 'org.springframework.boot:spring-boot-starter-jdbc' // 추가
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'// jdbc도 포함한다
runtimeOnly 'com.h2database:h2' // client
testImplementation('org.springframework.boot:spring-boot-starter-test') {
          exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
}}
  • resources/application.properties 스프링 부트에 JPA 설정 추가
    • show-sql : JPA가 생성하는 SQL 출력
    • ddl-auto : 테이블을 자동으로 생성하는 기능
spring.datasource.url=jdbc:h2:tcp://localhost/~/test
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.username=sa

spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=none
  • org.springframework.transaction.annotation.Transactional
  • JPA를 통한 모든 데이터 변경은 트랜젝션 안에서 실행되어야 함

 

6. 스프링 데이터 JPA

# 스프링 데이터 JPA

  • 스프링 부트 + JPA만 사용해도 개발 생산성이 증가하지만, 스프링 데이터 JPA를 사용한다면, 리포지토리에 구현 클래스 없이 인터페이스 만으로 개발이 가능
    • 반복되는 CRUD 기능 모두 제공
    • 개발자는 핵심 비즈니스 로직만 개발하면 됨
  • 페이징 기능 자동 제공 
  • +) 복잡한 동적 쿼리는 Querydsl 라이브러리 사용