Why I can't find my tables in H2 schema / How can I validate which H2 schema my Spring boot app is working with?

安稳与你 提交于 2019-12-12 04:01:28

问题


I'm running a spring boot app

didn't have any setting for h2 other than maven

when i'm connecting to the h2 console i can see the tables that were supposed to be created for two entities

i connected with the JDBC URL: jdbc:h2:mem:testdb (which is supposed to be the default)

Is there a way to make sure what schemas is H2 currently running/ or some log file for H2 ?

in my application.properties i have this:

spring.h2.console.enabled=true
spring.h2.console.path=/h2

I read somewhere that H2 initializing itself upon login, but a demo i was watching these were the exact steps taken , so not sure that is the case.

these are the settings in the H@ console:


回答1:


You can explicitly instruct spring boot to create and connect to a particular schema in H2 with config as below.

spring.datasource.url=jdbc:h2:~/test;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=sa

This creates a datasource of name test database in h2 in file mode. There would be a file called test.db in your home folder which would be the data file for the database.

DB_CLOSE_ON_EXIT property decides to recreate the database on every restart.




回答2:


I actually saw the right schema all along

The reason I thought I wasn't seeing the right schema was - the JPA Entities I expected to see, were not there.

I then found that this was because I didn't name the package for the JPA entities correctly

I named it "domain" (see pic):

I should have named it com.example.domain as can be seen:

This is because Spring Boot looks is doing a @ComponentScan "under" the package with the main class , so I had to prefix the "domains" with the name of the package that the main class resides in, which is com.example.




回答3:


There is an easier way to tell Spring JPA the default schema for your H2 data source by just adding the "SET SCHEMA {default schema}" in the datasource url, e.g.:

spring.datasource.url=jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1;INIT=CREATE SCHEMA IF NOT EXISTS testdb\\;SET SCHEMA testdb


来源:https://stackoverflow.com/questions/43560441/why-i-cant-find-my-tables-in-h2-schema-how-can-i-validate-which-h2-schema-my

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!