Kamil Janowski
Kamil Janowski

Reputation: 2025

Permanent database with 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;
}

Upvotes: 3

Views: 1737

Answers (2)

Kamil Janowski
Kamil Janowski

Reputation: 2025

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.

Upvotes: 1

Vignesh
Vignesh

Reputation: 531

May be try setting auto commit to true in the config/ property file. It may work

Upvotes: 0

Related Questions