[DB] 임베디드 모드

hi·2022년 12월 27일
0
  • H2 데이터베이스는 자바로 개발되어 있고 JVM안에서 메모리 모드로 동작하는 기능이 있다
  • DB를 애플리케이션에 내장하여 함께 실행
  • 애플리케이션이 종료되면 H2 데이터베이스 함께 종료. 데이터도 모두 사라짐

직접 사용

@Bean
@Profile("test")
public DataSource dataSource() {
	log.info("메모리 데이터베이스 초기화");
	DriverManagerDataSource dataSource = new DriverManagerDataSource();
	dataSource.setDriverClassName("org.h2.Driver");
	dataSource.setUrl("jdbc:h2:mem:db;DB_CLOSE_DELAY=-1");
	dataSource.setUsername("sa");
	dataSource.setPassword("");
	return dataSource;
}

@Profile("test") : 프로필이 test인 경우 데이터소스를 스프링 빈으로 등록

dataSource()

  • jdbc:h2:mem:db : 임베디드 모드(메모리 모드)로 동작하는 H2 DB 사용 가능
  • DB_CLOSE_DELAY=-1 : 임베디드 모드에서 데이터베이스 커넥션 연결이 모두 끊어지면 데이터베이스도 종료되는데 그것을 방지

스프링 부트 - DB 초기화 기능

  • 메모리 DB는 애플리케이션이 종료될 때 함께 사라짐
    따라서 애플리케이션 실행 시점에 데이터베이스 테이블도 새로 만들어주어야 한다

src/test/resources/schema.sql 파일 생성

drop table if exists item CASCADE;
create table item
(
 id bigint generated by default as identity,
 item_name varchar(10),
 price integer,
 quantity integer,
 primary key (id)
);

참고) 공식 매뉴얼
https://docs.spring.io/spring-boot/docs/current/reference/html/howto.html#howto.datainitialization.using-basic-sql-scripts

  • SQL 스크립트 로그 확인

src/test/resources/application.properteis

#schema.sql
logging.level.org.springframework.jdbc=debug

스프링 부트 제공

  • 스프링에서 임베디드 모드를 지원하는 데이터베이스를 사용하는 경우,
    데이터베이스에 대한 특별한 설정이 없으면 임베디드 데이터베이스 사용
  • 테스트 케이스에 @Transaction 사용

src/test/resources/application.properties

spring.profiles.active=test
#spring.datasource.url=jdbc:h2:tcp://localhost/~/testcase
#spring.datasource.username=sa
  • spring.datasource.url , spring.datasource.username 를 사용하지 않도록 주석처리

  • 로그 확인시 jdbc:h2:mem 뒤에 임의의 데이터베이스 이름이 붙음

  • 여러 데이터소스가 사용될 때 같은 데이터베이스를 사용하면서 발생하는 충돌을
    방지하기 위해 스프링 부트가 임의의 이름을 부여

	conn0: url=jdbc:h2:mem:d8fb3a29-caf7-4b37-9b6c-b0eed9985454
  • jdbc:h2:mem:testdb 로 고정하고 싶으면 application.properties에 설정 추가
	spring.datasource.generate-unique-name=false

0개의 댓글