spring

spring boot h2 database not found 관련(multiple datasource)

질주하는구 2022. 4. 13. 11:09

spring boot 에서 내장 database(h2)를 사용할때 application.properties 에 

spring.datasource.url=jdbc:h2:mem:test
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=

와 같이 작성을 해주면 어플리케이션이 시작 할때 자동으로 관련 database를 생성 해주게 됩니다.

(특정 버전 이전에는 위의 설정이 없어도 자동으로 생성 해주었는데 현재는 설정이 있어야 생성 된다고 합니다.)

https://howtodoinjava.com/spring-boot2/h2-database-example/

 

Spring Boot with H2 Database (In-Memory Database)

Learn to configure Spring boot with H2 database to create and use an in-memory database in runtime for unit testing or POC purposes.

howtodoinjava.com

위와 같이 사용하는 경우 크게 신경쓰지 않고 작업이 가능 합니다. 문제가 생기는건 해당 DB에 접근 하기 위한 datasource를 다중으로 구성하는 경우 입니다.

이 경우 

https://www.baeldung.com/spring-data-jpa-multiple-databases

내용을 참고 해서 서비스를 시작 하면 

위의 사진가 같이 mem:test database를 찾지 못해서 접속이 되지 않는 문제가 발생됩니다.

관련 내용을 찾아 보다 아래와 같은 글을 발견 했습니다.

https://stackoverflow.com/questions/55349373/database-not-found-and-ifexists-true-so-we-cant-auto-create-it

 

Database not found, and IFEXISTS=true, so we cant auto-create it

I am getting error after opening the h2 database console. I enter database name but it is showing database not found error: Database "C:/Users/Barlekar/onlineshoppings" not found, and IFEXISTS...

stackoverflow.com

위의 다중 datasource와는 상관 없는데 url을 jdbc:h2:~/test 으로 변경 하는 경우

정상적으로 database에 접속 할 수 있게 됩니다.

위의 url로 설정하는 경우 DB파일이 C:\Users\user-name\test.mv.db 경로로 생성 됩니다.

위와 같이 물리적 파일을 생성하는 url의 경우 다중 설정이 정상적으로 생성 되게 됩니다.

위와 같이 url을 물리적 파일 기준으로 작성 하는경우

spring.datasource.url=jdbc:h2:~/test
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=

spring.datasource2.url=jdbc:h2:~/test2
spring.datasource2.driverClassName=org.h2.Driver
spring.datasource2.username=sa
spring.datasource2.password=

spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.H2Dialect
#파일형의 경우 초기 생성 후 database가 유지 되기 때문에 아래 설정은 한번만 실행 시켜야 합니다.
spring.sql.init.mode=always

2개의 database를 사용해도 2개 모두 정상적으로 초기 생성 되게 됩니다.

 

(문제 현상에 대한 완벽한 이해 없이 우선 발생한 상황에 대해서만 기술한 내용 입니다. 문제에 대한 이해가

완료 되면 해당 문서를 갱신 할 예정 입니다.)

반응형