
h2 Database 설정하기
DB 접근 코드를 작성하기에 앞서 h2 DB부터 설치해주자.
우선 gradle에서 h2 관련 dependency를 추가한다.
build.gradle
dependencies {
...
runtimeOnly 'com.h2database:h2'
...
}
이제 DB 서버를 열 차례다.
아래의 사이트에서 다운로드 받거나, application.yml (application.properties)를 수정해서 서버를 열 수 있다.
난 다운로드 받지 않고 application.yml을 조금 더 수정하는 방식으로 했다.
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
www.h2database.com
다운로드 받는 방식으로 하는 경우 파일을 다운로드 받고 h2.bat 파일을 실행하면 자동으로 서버가 열린다.
이제 Spring에서 DB에 접근할 수 있도록 application.yml을 수정해주자.
application.yml
spring:
datasource:
url: jdbc:h2:~/test
driver-class-name: org.h2.Driver
username: sa
application.properties일 경우 아래와 같이 수정하면 된다.
application.properties
spring.datasource.url=jdbc:h2:~/test
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.username=sa
만약 h2 Database를 다운로드 받지 않았을 경우 아래의 코드를 추가해주면 된다.
yml 파일의 경우 h2: 앞에 띄어쓰기를 빼먹지 않도록 주의하자.
application.yml
spring:
...
h2:
console:
enabled: true
path: /h2-console
application.properties
...
spring.h2.console.enabled=true
spring.h2.console.path=/h2-console
이제 서버를 실행하고 아래의 주소로 접근하면 h2 콘솔 창이 열린다.
(DB를 직접 다운로드 받은 경우 h2.bat 실행과 동시에 콘솔 창이 열렸을 것이다.)
http://localhost:8080/h2-console
아래와 같은 창이 뜨면 성공이다.

JDBC URL을 jdbc:h2:tcp://localhost/~/test에서 jdbc:h2:~/test로 바꿔주고 연결했을 때 로그인이 되면 성공이다.

출처
'Study > Spring Boot' 카테고리의 다른 글
[Spring Boot] 스프링 통합 테스트 케이스 만들기 (0) | 2022.02.15 |
---|---|
[Spring Boot] JdbcTemplate로 MemoryRepository 대체하기 (0) | 2022.02.14 |
[Spring Boot] h2 DB에 TCP 접근 시 SocketTimeoutException 뜰 때 (0) | 2022.02.14 |
[Spring Boot] 회원가입, 회원조회 기능 구현 (0) | 2022.02.13 |
[Spring Boot] 의존성 주입과 스프링 빈 등록 (0) | 2022.02.13 |