Skip to content

Instantly share code, notes, and snippets.

@benelog
Last active May 11, 2019 15:58
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save benelog/2fd67baa839586ce9fb2 to your computer and use it in GitHub Desktop.
Save benelog/2fd67baa839586ce9fb2 to your computer and use it in GitHub Desktop.
h2 DB사용법

별도의 DB설치 없이 사용할 수 있어서, 테스트, 교육용, 패키지용 소프트웨어에서 사용핧만하다.

1. 의존성 추가

pom.xml에 추가한다.

<dependency>
    <groupId>com.h2database</groupId>
    <artifactId>h2</artifactId>
    <version>1.4.181</version>
</dependency>

2. 어플리케이션에서의 DataSource 설정

다른 DB와 동일하다. properties 파일 등에 선언하고 DataSource선언에서 참조한다.

driverClassName=org.h2.Driver
url=jdbc:h2:~/apps/h2db/crm;AUTO_SERVER=TRUE
username=sa
password=sa
maxActive=20

url에서 AUTO_SERVER=TRUE 추가하면 여러 프로세스에서 동시에 접속이 가능한다. 파일을 직접 읽거나 TCP connection으로 연결하는 방식을 알아서 선택한다.

3. DB접속

pom.xml의 plugin선언에 아래와 같이 추가한다.

    <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>exec-maven-plugin</artifactId>
        <version>1.1</version>
        <configuration>
            <mainClass>org.h2.tools.Console</mainClass>
            <arguments>
                <argument>-browser</argument>
            </arguments>
        </configuration>
   </plugin>

exec:java 골을 실행하면 웹브라어져가 실행되고 DB접속정보를 입력한다.

mvn exec:java

H2DB외의 다른 DB접속에도 사용할 수 있다. https://github.com/benelog/web-db-console 참조

4. 스키마 초기화

직접 DB에 접속해서 DDL을 실행할수도 있다. 어플리케이션 시작시에 자동으로 반영하고 싶다면 아래와 같이 Spring의 jdbc:initialize-database 선언을 이용한다.

<jdbc:initialize-database data-source="dataSource" ignore-failures="ALL">
	<jdbc:script location="classpath:db/user.sql"/>
	<jdbc:script location="classpath:db/product.sql"/>
</jdbc:initialize-database>

ignore-failures="ALL' 속성이 있기 때문에 이미 반영된 후에 재생성 때 나는 에러는 무시된다.

스키마가 변경되는것을 계속 반영하고 싶다면 아래의 도구들을 사용하는것이 좋다.

@urangurang
Copy link

감사합니다. 잘 보고 갑니다.

2번 어플리케이션에서의 DataSource 설정 부분에 오타 하나 있습니다~
driverClassNameorg.h2.Driver
driverClassName=org.h2.Driver

@sjyun
Copy link

sjyun commented Aug 2, 2018

이렇게 훌륭한 자료가 있는데.. edwith 교육자료에도 반영되면 정말~ 좋겠습니다.~~~

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment