H2 集成测试数据库不遵循与 MySQL prod DB 相同的命名

H2 Integration Test Database not following the same naming as MySQL prod DB

我一直在编写一些使用内存 (H2) 数据库的集成测试,但我一直卡在这个错误上。

Caused by: org.h2.jdbc.JdbcSQLException: Table "TESTTABLE" not found; SQL statement:

问题是,在生产环境中,Hibernate 正在将 table 名称和列名称从驼峰式外壳更改为下划线。 (TestTable -> test_table) 但对于 H2 测试数据库,它只是大写 (TestTable -> TESTTABLE)

这是我的测试配置 class:

@Configuration
@EnableJpaRepositories(basePackageClasses = {
    TestTableRepository.class
})
public class InMemoryDataConfig {

@Bean
public DataSource dataSource() {
    return new EmbeddedDatabaseBuilder()
            .setType(EmbeddedDatabaseType.H2)
            .addDefaultScripts()
            .build();
}

@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
    LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
    em.setDataSource(dataSource());
    em.setPackagesToScan(new String[]{"org.test.domain.entity"});

    JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
    em.setJpaVendorAdapter(vendorAdapter);
    em.setJpaProperties(buildHibernateProperties());

    return em;
}

protected Properties buildHibernateProperties() {
    Properties hibernateProperties = new Properties();

    hibernateProperties.setProperty("hibernate.dialect", "org.hibernate.dialect.HSQLDialect");
    hibernateProperties.setProperty("hibernate.show_sql", "true");
    hibernateProperties.setProperty("hibernate.use_sql_comments", "true");
    hibernateProperties.setProperty("hibernate.format_sql", "true");

    return hibernateProperties;
}

@Bean
public PlatformTransactionManager transactionManager(EntityManagerFactory emf) {
    JpaTransactionManager transactionManager = new JpaTransactionManager();
    transactionManager.setEntityManagerFactory(emf);
    return transactionManager;
}

@Bean
public TestService testService() {
    return new TestService();
}

}

我宁愿不必注释所有内容,这样测试就可以知道名称是什么。

对解决这个问题有什么想法或建议吗?感谢您的帮助!

这并不能完全回答我提出的具体问题,但我能够以更简单的方式让它工作。如果您废弃我在原始问题中发布的所有内容,您只需要做几件事。

首先你必须包含依赖项。我正在使用 gradle 所以我刚刚添加了这个:

testCompile("com.h2database:h2:1.4.191")

接下来,将这些注释添加到您的测试中:

@RunWith(SpringRunner.class)
@SpringBootTest
public class MultifamilyIntegrationTest {

    @Autowired
    protected TestService testService;

    @Test
    public void test() {
        testService.getUsers();
    }

}

最后,您必须在 /src/test/resources 文件夹中包含一个 data.sql 和一个 schema.sql 文件。

The schema.sql file is a creation script for everything schema related.

The data.sql file is to insert all of the needed data.