【问题标题】:Spring integration with JPASpring 与 JPA 的集成
【发布时间】:2018-12-21 17:21:06
【问题描述】:

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

我在 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 创建的,但是当我想查询它时,它说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 类,现在使用表名的大写版本。但是没有解决。

解决办法是什么?是否有两个数据库实例?

【问题讨论】:

标签: hibernate spring-data-jpa h2


【解决方案1】:

确实,每个连接都会访问不同的数据库实例。

在DataSource对象的url设置处使用jdbc:h2:mem:H2DatabaseTest:DB_CLOSE_DELAY=-1

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

【讨论】:

    猜你喜欢
    • 2023-03-12
    • 1970-01-01
    • 2017-09-22
    • 1970-01-01
    • 2020-07-05
    • 2018-09-30
    • 1970-01-01
    • 1970-01-01
    • 2012-08-07
    相关资源
    最近更新 更多