-
[spring boot] 스프링 부트 h2 인메모리 db 시작하기Spring/spring boot 및 기타 2021. 4. 27. 18:29
외부에 물리db 를 생성하기 어려울떄가 있다.
나 같은 경우 사이드 프로젝트를 하고 싶은데 물리 db 를 생성하기 부담스러울때 간단히 내부 db 를 사용하고 싶어 인메모리 h2 를 사용한다.
h2 는 보통 프로덕션보다는 보통 test 용으로 사용한다.
왜냐면 휘발성이기 때문이다.
- 디스크가 아닌 주 메모리에 모든 데이터를 보유하고 있는 데이터베이스입니다.
- 디스크 검색보다 자료 접근이 훨씬 빠른 것이 큰 장점입니다. 단점은 매체가 휘발성이기 때문에 DB 서버가 꺼지면 모든 데이터가 유실된다는 단점이 있습니다.
- 스프링 부트에서 H2, HSQL 같은 인메모리, 디스크 기반 DB를 지원합니다.
라이브러리 추가
현재 spring boot 버젼 2.4.5
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> <scope>runtime</scope> </dependency>
- H2 데이터베이스 의존성을 추가하고 난 후, 설정 파일에 아무 설정이 되어 있지 않으면 스프링 부트는 자동적으로 H2 데이터베이스를 기본 데이터베이스로 선택한다
- spring-boot-starter-jdbc 의존성을 추가하면 DataSource, JdbcTemplate을 별다른 설정없이 @Autowired 같은 빈 주입 어노테이션만 가지고도 쓸 수 있다.
@Component public class H2Runner implements ApplicationRunner { @Autowired DataSource dataSource; @Autowired JdbcTemplate jdbcTemplate; @Override public void run(ApplicationArguments args) throws Exception { try(Connection connection = dataSource.getConnection()){ System.out.println(connection); String URL = connection.getMetaData().getURL(); System.out.println(URL); String User = connection.getMetaData().getUserName(); System.out.println(User); Statement statement = connection.createStatement(); String sql = "CREATE TABLE USER(ID INTEGER NOT NULL, NAME VARCHAR(255), PRIMARY KEY (ID) )"; statement.executeUpdate(sql); } jdbcTemplate.execute("INSERT INTO USER VALUES(1, 'testuser')"); } }
위의 코드 까지만 작성하면 h2 가 정상적으로 동작하는 지 확인 가능하다.
아래 기본 ddl sql 로드 방법을 사용하면 위의 자바 class 는 필요가 없다.
spring: h2: console: enabled: true path: /h2-console
다음과 같이 yml 에 설정하면 웹에서 sql 접근 가능
localhost:8080/h2-console 로 접근 가능
별도의 yml 로 디비 접속 설정을 안하면
connection.getMetaData().getURL() -> JDBC URL
connection.getMetaData().getUserName() -> User Name, 디폴트값 : sa
로 로그 찍은 값으로 접속 가능하다.
디폴트 값으로 하지 않고 yml 에서 설정하려면
datasource: url: jdbc:h2:mem:testdb username: sa
다음과 같이 작성하면 된다.
기본 ddl sql script 로드
기본적으로 jpa 와 h2 라이브러리 import 하는 거 만으로 schema.sql 과 data.sql 를 초기에 로딩 할 수 있다.
스키마 파일은
schema.sql 로 명명 하고
resources > 하위에 schema.sql 을 두면 초기 구동 되면서 sql 문을 실행한다.
CREATE TABLE Employee ( id integer NOT NULL, firstName varchar(255) not null, lastName varchar(255) not null, email varchar(255), phoneNumber varchar(255), hireDate timestamp, salary integer, commissionPct integer, primary key(id) );
data 삽입도 같이 data.sql 파일안에 insert 문을 넣어주면 된다.
별도로 해줘야 할 작업은 application.yml 파일에
spring: jpa: hibernate: ddl-auto: none
같이 ddl-auto 를 none 으로 설정해야 resources 하위의 sql 문을 실행한다.
지금 하는 sql 초기 구동시 로딩을 해주면 위에서 작성한 H2Runner.class 를 따로 생성하지 않아도 된다.
결과
최종 yml 파일
spring: h2: console: enabled: true path: /h2-console jpa: hibernate: ddl-auto: none datasource: url: jdbc:h2:mem:testdb username: sa
반응형'Spring > spring boot 및 기타' 카테고리의 다른 글
[spring boot] mybatis 연동 및 설정 (0) 2021.06.23 [spring boot] 스프링 firebase database 사용하기 (1) 2021.05.04 [spring] 스프링 HikariDatasource 속성 값 (0) 2021.03.31 [spring] 스프링 elasticsearch NativeSearchQuery 사용방법 (0) 2021.03.16 [spring] 스프링 elasticsearch ElasticsearchRepository underscore 오류 해결방법 (0) 2021.03.16