0

I would like to ask you to point my err in the following setup.

I am using JPA with Spring, more specifically Hibernate. I would like to use H2 in memory database with JPA.

My SpringConfiguration is as follows:

 @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
        LocalContainerEntityManagerFactoryBean emf
                = new LocalContainerEntityManagerFactoryBean();
        emf.setDataSource(getDataSource());
        emf.setPackagesToScan(new String[] { "com.some.package" });

    JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
    emf.setJpaVendorAdapter(vendorAdapter);
    emf.setJpaProperties(additionalProperties());

    return emf;
}

@Bean
public DataSource getDataSource() {
    DriverManagerDataSource dataSource = new DriverManagerDataSource();
    dataSource.setDriverClassName("org.h2.Driver");
    dataSource.setUrl("jdbc:h2:mem:H2DatabaseTest");
    dataSource.setUsername( "user" );
    dataSource.setPassword( "user" );
    return dataSource;
}

Properties additionalProperties() {
    Properties properties = new Properties();
    properties.setProperty("hibernate.hbm2ddl.auto", "create-drop");
    properties.setProperty("hibernate.hbm2ddl.import_files", "/init-db-test.sql");
    properties.setProperty("hibernate.dialect", "org.hibernate.dialect.H2Dialect");
    properties.setProperty("hibernate.id.new_generator_mappings", "true");
    properties.setProperty("hibernate.show_sql", "true");
    properties.setProperty("hibernate.format_sql", "true");

    return properties;
}

```

My problem is that the a table with Entity class gets created by Hibernate, but then when I want to query it, it says that Table "MYENTITYCLASS" not found.

create table MYENTITYCLASS(
       id bigint not null,
        applicationId varchar(255),
        name varchar(255),
        status varchar(255),
        timeOfRecord bigint,
        primary key (id)
    )

So I have annotated the Entity class with @Table(name = "MYENTITYCLASS") and use now the upper case version of the table name. But it did not solve.

What is the solution? Are there two database instances?

  • Possible duplicate of [Set table name in Spring JPA](https://stackoverflow.com/questions/38646025/set-table-name-in-spring-jpa) – Jacob Jul 13 '18 at 10:46
  • This solved: https://stackoverflow.com/questions/10314216/in-memory-database-is-not-created-but-logs-shows-that-ddl-was-executed – Bálint Harmath Jul 24 '18 at 13:29

1 Answers1

0

Indeed there are different database instances reached at each connection.

Use jdbc:h2:mem:H2DatabaseTest:DB_CLOSE_DELAY=-1 at the url setting of the DataSource object.

This means that the connection won't close after having used it, but will remain open an can be used again. Thus the created database's tables can be reached as well.