Develop/Spring Boot
24. Support InMemory DB
자라선
2020. 7. 27. 17:05
지원하는 인-메모리 데이터베이스
· H2 (추천, 콘솔 때문에...)
· HSQL
· Derby
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
Spring-JDBC가 클래스패스에 있으면 자동 설정이 필요한 빈을 설정 해줍니다.
o DataSource
o JdbcTemplate
SpringBoot의 @EnableAutoConfiguration 어노테이션에서 2개의 설정을 실행한다.
org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration,\
org.springframework.boot.autoconfigure.jdbc.JdbcTemplateAutoConfiguration
별도의 설정없이 바로 실행한다면 인-메모리 DB로 실행한다.
설정코드
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.Statement;
@Component
public class H2Runner implements ApplicationRunner {
@Autowired
JdbcTemplate jdbcTemplate;
@Autowired
DataSource dataSource;
@Override
public void run(ApplicationArguments args) throws Exception {
//try-with-resources를 사용하여 자동 close
try(Connection connection = dataSource.getConnection()){
System.out.println(connection.getMetaData().getURL());
System.out.println(connection.getMetaData().getUserName());
Statement statement = connection.createStatement();
String sql = "CREATE TABLE TEST(ID INT PRIMARY KEY, NAME VARCHAR(255));";
statement.executeUpdate(sql);
}
String sqlInsert = "INSERT INTO TEST VALUES(1, 'Hello');";
String sqlInsert2 = "INSERT INTO TEST VALUES(2, 'World');";
jdbcTemplate.execute(sqlInsert);
jdbcTemplate.execute(sqlInsert2);
}
}
테스트 코드
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.test.context.junit4.SpringRunner;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import static org.assertj.core.api.Assertions.assertThat;
@RunWith(SpringRunner.class)
@SpringBootTest
public class H2RunnerTest {
@Autowired
JdbcTemplate jdbcTemplate;
@Test
public void h2Test() throws SQLException {
String sqlSelect = "SELECT * FROM TEST;";
List<Map<String, Object>> list = jdbcTemplate.queryForList(sqlSelect);
assertThat(list.get(1).get("NAME")).isEqualTo("World");
}
}
H2 콘솔 사용하는 방법
· spring-boot-devtools를 추가하거나...
· spring.h2.console.enabled=true 만 추가.
· /h2-console로 접속 (이 path도 바꿀 수 있음)