Spring H2 embedded database [duplicate]
Asked Answered
T

4

5

I want to create an in-memory database populated with test data for fast testing, so I declare this bean in my configuration file, but I also want so set this properties:

MODE=MySQL
DB_CLOSE_ON_EXIT=FALSE

but I don't know where to do it

@Bean
public DataSource dataSource(){
    return
        (new EmbeddedDatabaseBuilder())
        .setType(EmbeddedDatabaseType.H2) //.H2 
        .addScript("classpath:db/H2.schema.sql")
        .addScript("classpath:db/H2.data.sql")
        .build();
}
Tuinenga answered 24/4, 2017 at 18:35 Comment(0)
H
15

try this

@Bean
public DataSource dataSource(){
    return
        new EmbeddedDatabaseBuilder()
        .setType(EmbeddedDatabaseType.H2)
        .setName("testDB;DB_CLOSE_ON_EXIT=FALSE;MODE=MySQL") 
        .addScript("classpath:db/H2.schema.sql")
        .addScript("classpath:db/H2.data.sql")
        .build();
}
Hera answered 24/4, 2017 at 19:3 Comment(2)
beat me on the minute :POgata
Solved my issue. Thanks :)Untaught
O
4

You can try using EmbeddedDatabaseBuilder.setName()

@Bean
public DataSource dataSource() {
return
    new EmbeddedDatabaseBuilder()
    .setName("testdb;MODE=MySQL;DB_CLOSE_ON_EXIT=false")
    .setType(EmbeddedDatabaseType.H2) //.H2 
    .addScript("classpath:db/H2.schema.sql")
    .addScript("classpath:db/H2.data.sql")
    .build();
}

Note: I have not tried this myself, but found a clue on this answer

Ogata answered 24/4, 2017 at 19:4 Comment(0)
F
2

An alternative approach is to wire DataSources using properties. This way, you can set the JDBC URL which can contain additional properties.

Faeroese answered 24/4, 2017 at 18:53 Comment(0)
C
2

The mode can be done via a SQL statement on H2, but I am pretty sure the DB_CLOSE_DELAY must be set as part of the URL which there is no easy hook into. You would be best just setting this in the application.properties/yml and let spring autoconfigure it

jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1;MODE=MySQL would be the spring.datasource.url additional properties are available for the schema and data

Chev answered 24/4, 2017 at 19:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.