Search code examples
springh2embedded-database

My Spring Database (H2) is not Persisting


This is my config file

@Configuration
@ComponentScan
public class Config {

@Bean
public DataSource datasource() {
    return new EmbeddedDatabaseBuilder().setName("MyDB").setType(EmbeddedDatabaseType.H2).addScript("schema.sql").build();
}

@Bean
public JdbcOperations jdbcTemplate(DataSource ds) {
    return new JdbcTemplate(ds);        
}
}

After I run the program, I can not find the "MyDB" database.

I know it is an in-memory database. How to make it embedded so that when I close the program the data on the database persist and I can find "MyDB" on the project folder.


Solution

  • @Bean
    public DataSource h2DataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName(driver);
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        return dataSource;
    }
    
    driver: org.h2.Driver
    url: jdbc:h2:file:${java.io.tmpdir}/database/db_name;AUTO_SERVER=TRUE
    username: user
    password: pass