본문 바로가기
Dev/Spring Boot

[스프링 부트 개념과 활용] 스프링 데이터 2부

by dev_jsk 2020. 8. 27.
728x90
반응형

인메모리 데이터베이스

Application Server의 메모리를 이용하는 데이터베이스 시스템

 

종류

  • H2
  • HSQL
  • Derby

특징

  • Jdbc 의존성을 추가하면 자동 설정이 필요한 DataSource, JdbcTemplate Bean을 설정해준다.
  • 디스크가 아닌 메모리에 데이터가 존재해 접근이 빠르다.
  • 메모리에 데이터가 존재하여 휘발성을 가진다.

H2 DB 예제

// pom.xml
// jdbc
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
// h2
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
// H2Runner.java
@Component
public class H2Runner implements ApplicationRunner {
@Autowired
DataSource dataSource;
@Autowired
JdbcTemplate jdbcTemplate;
@Override
public void run(ApplicationArguments args) throws Exception {
// try-with-resource : Java 7 이상
// try()에 선언된 객체를 코드블럭 안에서 사용하고 코드블럭을 벗어나면
// 자동으로 close()를 호출한다.
// 기존 try-cath-finally문 처럼 finally 를 사용해서 close() 할 필요가 없다.
try(Connection connection = dataSource.getConnection()) {
// 인메모리 데이터베이스 정보 확인
String url = connection.getMetaData().getURL();
String userName = connection.getMetaData().getUserName();
System.out.println("URL : " + url);
System.out.println("UserName : " + userName);
Statement statement = connection.createStatement();
String sql = "CREATE TABLE USER(ID INTEGER NOT NULL, NAME VARCHAR(255), PRIMARY KEY (ID))";
statement.executeUpdate(sql);
}
// JdbcTemplate 를 사용하면 코드를 간결하게 사용 가능하고
// resource 반납처리 기능이 구현되어 있어 안전하게 사용 가능하며
// 예외를 던질 때 에러 계층구조가 잘 되어있어 가독성이 높은 에러 메시지 확인 가능하다.
jdbcTemplate.execute("INSERT INTO USER VALUES (1, 'Jinseo')");
}
}

H2 Console 사용 방법

  • spring-boot-devtools 추가
  • application.propertiesspring.h2.console.enabled=true 설정

 

H2 Console 이용 결과 확인

728x90
반응형

댓글