본문 바로가기
Backend, Server/JPA

[JPA] H2 데이터베이스 사용법, JPA 시작하기

by ggyongi 2021. 12. 8.
반응형

1. 설치

다운로드 : http://h2database.com

 

H2 Database Engine (redirect)

H2 Database Engine Welcome to H2, the free SQL database. The main feature of H2 are: It is free to use for everybody, source code is included Written in Java, but also available as native executable JDBC and (partial) ODBC API Embedded and client/server mo

h2database.com

윈/맥에 맞게 windows 또는 all platforms를 다운받으면 된다.

 

2. 실행

설치 경로로 가서 bin 디렉토리 내의 h2.bat 파일을 클릭하면 서버모드로 H2가 실행된다.

 

 

 

3. 데이터베이스 생성

h2 1.4.198 이후 버전부터는 보안 문제로 데이터베이스가 자동으로 생성되지 않는다고 한다. 그래서 위처럼 미리 데이터베이스를 생성하지 않고 JDBC URL을 입력하고 연결하려고 하면 에러가 발생한다.

 

그럼 어떻게 해야되나?

위와 같이 JDBC URL을 입력해주면 된다. 이때 hello대신 원하는 이름을 넣어주면 된다.

그리고 연결하기를 누르면 데이터베이스가 생성된다.

그럼 아래와 같은 경로에 hello.mv라는 파일이 생성된 것을 확인할 수 있다. 

+) 근데 이것도 안되는 경우가 있는데 나의 경우엔 h2 서버를 닫고 재실행하면 다시 정상 실행되었다.

 

 

4. 데이터베이스 접속

이후 만들어준 데이터베이스에 접속할 때는 JDBC URL을 jdbc:h2:tcp://localhost/~/hello로 바꿔줘야 한다.

JDBC URL을 저렇게 변경하는 이유는 파일 직접 접근이 아닌 TCP 소켓을 통해 접속해야 어플리케이션과 콘솔이 동시에 접근했을 때 오류가 발생하지 않기 때문이다.

이후 연결하면 끝!! 데이터베이스를 사용할 준비가 다 되었다. 

 

 

5. 스프링과 연결

build.gradle에 라이브러리를 추가

implementation 'org.springframework.boot:spring-boot-starter-jdbc'
runtimeOnly 'com.h2database:h2'

그리고 어떤 db에 붙을지를 알려줘야 하기 때문에 db 정보를 던져주면 된다.

application.properties에 다음과 같이 입력한다.

spring.datasource.url=jdbc:h2:tcp://localhost/~/test
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.username=sa

 

 

6. JPA 시작하기

JPA를 시작하기 위해 build.gradle에 라이브러리를 추가해야 한다.

이때 앞서 입력했던 implementation 'org.springframework.boot:spring-boot-starter-jdbc'는 빼줘도 된다.(jdbc도 포함하기 때문)

다음을 입력하자.

implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
runtimeOnly 'com.h2database:h2'

그리고 application.properties에 JPA 설정을 추가해줘야 한다.

spring.datasource.url=jdbc:h2:tcp://localhost/~/test 
spring.datasource.driver-class-name=org.h2.Driver 
spring.datasource.username=sa 

spring.jpa.show-sql=true 
spring.jpa.hibernate.ddl-auto=none
 

비전공자 네카라 신입 취업 노하우

시행착오 끝에 얻어낸 취업 노하우가 모두 담긴 전자책!

kmong.com

댓글