user3687431
user3687431

Reputation: 283

Spring-boot populate H2 database with schema.sql and data.sql

I set up Spring-boot to work with H2 in-memory database application.properties file is in the /config directory and it looks like, this file is processed

spring.datasource.url=jdbc:h2:mem:mydb;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.h2.console.path=/myconsole
spring.h2.console.enabled=true
spring.datasource.initialize=true
spring.datasource.schema=schema.sql
spring.datasource.data=data.sql

This file is processed and the console appears at /myconsole But the schema.sql and data.sql are not processed and db is empty. I placed schema.sql and data.sql files both under /config and /src/main/resources.

SQL language instructions are correct and I can populate the table using console input.

Another strange thing is even though i name db as

spring.datasource.url=jdbc:h2:mem:mydb

the spring console loads another database testdb

o.s.j.d.e.EmbeddedDatabaseFactory --- Starting embedded database: url='jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=false', username='sa'

How to load the H2 database correctly?

Upvotes: 14

Views: 31475

Answers (2)

Levent Divilioglu
Levent Divilioglu

Reputation: 11622

Followings are outdated;

spring.datasource.schema
spring.datasource.data

The replacements are;

spring.sql.init.schemaLocations
spring.sql.init.dataLocations

Related Class;

org.springframework.boot.sql.init.DatabaseInitializationSettings

Check replacements via additional-spring-configuration-metadata.json under META-INF directory of spring-boot-autocinfigure-3.3.5.jar.

Spring Boot version: 3.3.5

I don't know from which version exactly this replacement did occur but as of 3.3.5 it's as above.

Upvotes: 0

user3687431
user3687431

Reputation: 283

Resolved the issue.

The spring boot app requires its ownd jdbc dependency

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>

NON-boot dependency, that I had, is NOT enough alone:

<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-jdbc</artifactId>
</dependency>

Without the "spring-boot-starter-jdbc" dependency "spring.datasource.url" settings in file "application.properties" are not processed. That file is actually processed, but not the jdbc settings. Spring boot will create its own testdb in the memory, which destroys the data after closing the application.

Upvotes: 11

Related Questions