Notice
Recent Posts
Recent Comments
Link
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
Archives
Today
Total
관리 메뉴

개발자되기 프로젝트

H2 Database 설치 및 사용 법 본문

Spring Boot

H2 Database 설치 및 사용 법

Seung__ 2021. 7. 23. 17:13

2021.05.22 - [JPA] - H2 In-Memory DB

 

H2 In-Memory DB

1. H2 DB 란? DB는 JAVA기반의 경량화된 관계형 DB file 로 저장하여 실제 DB처럼 유지할 수 있고, memory DB로 사용하여 실제 인스턴스가 동작하는 시점에만 유지도 가능 프로젝트 초기 test DB로 사용 유지

bsh-developer.tistory.com

순서

  • H2 Db 설치
  • SQL을 통해 애플리케이션과 DB를 연결할 때 Jdbc사용
  • Jdbc너무 어려워...JdbcTemplate사용
  • 더 쉽게! JPA사용 : 쿼리없이 객체를 바로 DB에 저장 가능.
  • Spring Data JPA :  JPA를 편리하게 한번 더 감싸서 제공.

 

1. H2 DB 설치


 

H2 Database Engine

H2 Database Engine Welcome to H2, the Java SQL database. The main features of H2 are: Very fast, open source, JDBC API Embedded and server modes; in-memory databases Browser based Console application Small footprint: around 2 MB jar file size     Suppor

h2database.com

설치완료 후 콘솔 실행. : h2.bat을 실행하자.

h2.bat을 실행하면 콘솔창이 뜰 텐데, 해당 창을 끄면 DB가 종료되는 것과 같다.

 

사용할 때는 계속 켜두자. 귀찮다면. h2w.bat을 사용(콘솔창 꺼도 유지됨)

또는 간변하네 IDE에서 terminal을 이용

C:\Program Files (x86)\H2\bin>bin.bat

처음 실행된 화면

2) local에 DB생성 방법

 - jdbc:h2:~test 연결 

- ~/test.mb.db 파일 생성여부 확인

    사용자 폴더에 가면 확인할 수 있다. C:\Users\<userName>

 

위의 방식대로 파일에 직접 연결하면 동시에 접근이 불가능 할 수 있다.

 

 

-jdbc:h2:tcp://localhost/~/test 연결 

이후 부터는 접근할 때 jdbc:h2:tcp://localhost/~/test로 접근하면 소켓을 통해 접근이 가능.
   

 

 

3. Table 생성


 

JAVA에서 Long 타입은 DB에서는 bigint, String은 varchar로 설정.

Generated By Default As Identity : id를 입력하지 않고 DB에 들억면 DB설정값에 따라 입력됨.

 

 

 

4. Table 조회 : select *from member;


 

5. insert


 

 

6. 조회


 

7. H2 DB에 접근하기 위한 설정.

 - dependency 추가

   build.gradle에 아래와 같이 추가해 주자.

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

 

- application.properties

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

 

준비 끝! 인줄 알았는데 에러가 발생했다.user  name과 password를 입력하랜다.

org.h2.jdbc.JdbcSQLInvalidAuthorizationSpecException: 
Wrong user name or password [28000-200]

 

8. user name 추가!


Spring boot 2.4에서 패치가 진행되었다. 

2.4 부터는 아래와 같이 application.properties에 user name정보를 추가해 줘야 한다.

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

 

여기까지 하면 사용하는데 문제가 없다

 

Comments