본문 바로가기
학습/Spring

[spring] 스프링 부트에서 JDBC와 In-memory DB 사용하기

by KKambi 2020. 5. 5.

의존성 추가 (gradle)

  • implementation "org.springframework.boot:spring-boot-starter-jdbc"
  • runtimeOnly "com.h2database:h2"

 

사용할 수 있는 In-memory DB의 종류

  1. h2
  2. HSQL
  3. Derby

 

spring-jdbc의 자동설정

jdbc가 classpath에 존재하면 해당 빈을 등록하고 자동 설정

  • DataSource
  • JdbcTemplate

 

아무런 DataSource 설정이 없으면, 스프링 부트는 자동으로 In-memory DB 사용

확인해보자!

  1. Runner 클래스 생성
  2. DataSource 객체를 @Autowired로 주입받기
  3. @Override run 구현
    • DataSource 객체에서 JDBC Connection 객체 가져오기
    • Connection 객체에서 접속하는 DB의 URL과 UserName 가져오기
    • 기본 URL :  jdbc:h2:mem:testdb
    • 기본 UserName : SA
  4. Connection close
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@Component
public class SampleRunner implements ApplicationRunner {
 
    private static final Logger logger = LogManager.getLogger(SampleRunner.class);    
 
    @Autowired
    DataSource dataSource;
 
    @Override
    public void run(ApplicationArguments args) throws Exception
        try (Connection connection = dataSource.getConnection();){
            logger.info(connection.getMetaData().getURL());
            logger.info(connection.getMetatData().getUserName());
        }    
    }
}
cs
  1. 로거 사용
  2. try-with-resource로 connection객체는 자동으로 close
  3. 자동으로 빈 등록되는 DataSource

 

JDBC Connection을 이용한 SQL문 실행

  1. Connection객체로부터 Statement객체 생성
  2. String에 SQL문 할당
  3. Statement객체의 executeUpdate(sql) 메소드 실행
  4. Connection close
1
2
3
4
5
6
7
8
    @Override
    public void run(ApplicationArguments args) throws Exception {
        try(Connection connection = dataSource.getConnection();){
            Statement statement = connection.createStatement();
            String sql = "CREATE TABLE USER(ID INTEGER NOT NULL, name VARCHAR2(16), PRIMARY KEY (ID))";
            statement.executeUpdate(sql);
        }
    }
cs

 

 

H2-Console 접속하기 (/h2-console)

사용방법

  • spring-boot-devtools 의존성 사용
  • 프로퍼티 파일에 spring.h2.console.enabled=true

 

Connection보다 편리한 jdbcTemplate

자동으로 빈 등록됨

  • jdbcTemplate.execute(sql)
  • 기본 JDBC보다 간결함
  • 리소스 반납도 처리해줌
  • 예외 계층 구조도 잘 짜여져 있어 예외 던지기 편리함
1
2
3
4
5
6
7
8
9
10
11
@Component
public class H2Runner implements ApplicationRunner {
    @Autowired
    JdbcTemplate jdbcTemplate;
 
    @Override
    public void run(ApplicationArguments args) throws Exception {
        String sql = "CREATE TABLE USER(ID INTEGER NOT NULL, name VARCHAR2(16), PRIMARY KEY (ID))";
        jdbcTemplate.execute(sql);
    }
}
cs

댓글