Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Permanent database with H2

Tags:

java

spring

h2

I want my H2 database to be stored into a file, so that once I close the application and open it again, all the data that was previously written to the database is still there, but for some reason, at the moment whenever I start the application, the database is completely empty. Any suggestions?

@Bean
public DataSource dataSource() {
    File f = new File(".");
    JdbcDataSource ds = new JdbcDataSource();
    ds.setURL("jdbc:h2:file:" + f.getAbsolutePath() + "/db/aurinko");
    ds.setUser("");
    ds.setPassword("");
    return ds;
}

private Properties getHibernateProperties() {
    Properties prop = new Properties();
    prop.put("hibernate.format_sql", "true");
    prop.put("hibernate.show_sql", "false");
    prop.put("hibernate.dialect", "org.hibernate.dialect.H2Dialect");
    prop.put("hibernate.hbm2ddl.auto", "update");
    return prop;
}

@Bean
public SessionFactory sessionFactory() throws IOException {
    LocalSessionFactoryBuilder builder = new LocalSessionFactoryBuilder(dataSource());
    builder.scanPackages("io.aurinko.server.jpa").addProperties(getHibernateProperties());

    SessionFactory result = builder.buildSessionFactory();

    return result;
}
like image 959
Kamil Janowski Avatar asked Aug 23 '26 05:08

Kamil Janowski


1 Answers

I was using spring-boot. Turns out that spring-boot generates its own H2 database. That means that I had two separate databases, one of which I was trying to use and the second one (only the in-memory one) that I was actually using.

like image 154
Kamil Janowski Avatar answered Aug 24 '26 20:08

Kamil Janowski