4

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();
}
Nuñito Calzada
  • 4,394
  • 47
  • 174
  • 301

4 Answers4

14

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();
}
pezetem
  • 2,503
  • 2
  • 20
  • 38
3

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

YourAboutMeIsBlank
  • 1,787
  • 3
  • 18
  • 27
qtips
  • 625
  • 6
  • 17
2

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

ThomasRS
  • 8,215
  • 5
  • 33
  • 48
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

Darren Forsythe
  • 10,712
  • 4
  • 43
  • 54