H2 DB는 자바로 개발되어 있고, JVM 안에 메모리 모드로 동작하는 특별한 기능
어플리케이션을 실행할 떄 H2DB 도 해당 JVM 메모리에 포함해 함께 실행한다. DB를 앱에 내장해 함께 실행한다고 해서 임베디드 모드라고 불린다.
-> 앱에서 자바 메모리를 함께 사용하는 라이브러리 처럼 동작한다.
임베디드 모드는 편리하지만 테이블이 존재하지 않는 빈 DB이다. 그렇기 때문에 스프링에서 제공하는 기능으로 앱 실행 시마다 초기화 해주는 스크립트를 실행한다.
@Bean
@Profile("test")
public DataSource dataSource() {
log.info("메모리 DB 초기화");
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;
}
test 환경일 때 dataSource를 임베디드 모드 DB를 사용하도록 빈으로 등록한다.
(굳이 bean으로 등록하지 않더라도 test환경에선 DB에 대한 정보를 설정하지 않으면 임베디드 모드로 수행한다.)
resources 하위에 schema.sql을 작성하면 스프링에서 수행해준다.
drop table if exists itme CASCADE;
create table item
(
id bigint generated by default as identity,
item_name varchar(10),
price integer,
quantity integer,
primary key (id)
);