Dror
Dror

Reputation: 5505

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

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:

enter image description here

Upvotes: 1

Views: 4783

Answers (4)

Ahmed Aziz
Ahmed Aziz

Reputation: 427

For me I had to check the log when I run Sprinboot

jdbc:h2:mem:9967b201-6b59-4925-acb3-d2e50dc5d9a5.  --> this can be any other auto generated UUD

Adding this to your JDPC URL in the browser will let you see the tables that you created.

enter image description here

Upvotes: 1

tmwong
tmwong

Reputation: 116

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

Upvotes: 2

Dror
Dror

Reputation: 5505

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):

enter image description here

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

enter image description here

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.

Upvotes: 1

Praneeth Ramesh
Praneeth Ramesh

Reputation: 3564

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.

Upvotes: 3

Related Questions