与JPA的春季集成

时间:2018-07-13 10:37:11

标签: hibernate spring-data-jpa h2

我想请您在以下设置中指出我的错误。

我在Spring上使用JPA,更具体地说是在Hibernate中使用。 我想通过JPA在内存数据库中使用H2。

我的SpringConfiguration如下:

 @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;
}

```

我的问题是Hibernate创建了一个带有Entity类的表,但是当我要查询它时,它说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)
    )

因此,我用@Table(name = "MYENTITYCLASS")注释了Entity类,现在使用表名的大写版本。但这并没有解决。

解决方案是什么?有两个数据库实例吗?

1 个答案:

答案 0 :(得分:0)

实际上,每个连接都有不同的数据库实例。

在数据源对象的url设置中使用jdbc:h2:mem:H2DatabaseTest:DB_CLOSE_DELAY=-1

这意味着该连接在使用后将不会关闭,但将保持打开状态并可以再次使用。因此,也可以访问创建的数据库表。