Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I have H2 autocreate a schema in an in-memory database?

(I've already seen the H2 database In memory - Init schema via Spring/Hibernate question; it is not applicable here.)

I'd like to know if there's a setting in H2 that will allow me to auto-create a schema upon connecting to it. If it helps, I'm only interested in the in-memory case.

H2 supports various semicolon-separated modifiers at the end of the URL, but I didn't find one for automatically creating a schema. Is there such a feature?

like image 221
Laird Nelson Avatar asked Mar 07 '11 21:03

Laird Nelson


People also ask

Does H2 support schema?

CREATE is a generic SQL command used to create Tables, Schemas, Sequences, Views, and Users in H2 Database server.

Is H2 an in-memory database?

H2 is an embedded, open-source, and in-memory database. It is a relational database management system written in Java. It is a client/server application. It stores data in memory, not persist the data on disk.

How do I access H2 in-memory database?

Accessing the H2 Console H2 database has an embedded GUI console for browsing the contents of a database and running SQL queries. By default, the H2 console is not enabled in Spring. Then, after starting the application, we can navigate to http://localhost:8080/h2-console, which will present us with a login page.

How do I create a schema in H2 database in spring boot?

Creating Schema and Inserting Data on Initialization We may want to initialize the database with some fixed schema (DDL) and insert default data (DML) into tables before the application is ready for business usecases. We can achieve this by putting SQL files into the resources folder ( /src/main/resources/ ). schema.


2 Answers

Yes, H2 supports executing SQL statements when connecting. You could run a script, or just a statement or two:

String url = "jdbc:h2:mem:test;" +               "INIT=CREATE SCHEMA IF NOT EXISTS TEST" String url = "jdbc:h2:mem:test;" +               "INIT=CREATE SCHEMA IF NOT EXISTS TEST\\;" +                    "SET SCHEMA TEST"; String url = "jdbc:h2:mem;" +               "INIT=RUNSCRIPT FROM '~/create.sql'\\;" +                    "RUNSCRIPT FROM '~/populate.sql'"; 

Please note the double backslash (\\) is only required within Java. The backslash(es) before ; within the INIT is required.

like image 139
Thomas Mueller Avatar answered Oct 14 '22 09:10

Thomas Mueller


If you are using spring with application.yml, the following will work for you:

spring:   datasource:     url: jdbc:h2:mem:mydb;DB_CLOSE_ON_EXIT=FALSE;MODE=PostgreSQL;INIT=CREATE SCHEMA IF NOT EXISTS calendar 
like image 32
Marquis Blount Avatar answered Oct 14 '22 08:10

Marquis Blount