[英]Spring Boot @DataJpaTest without ddl generation
我在两个数据库中都有带MySQL的表,并想用SpringBoot(1.5.6.RELEASE)和JPA编写测试。 对于这一点,我用的是@DataJpaTest
连同@EntityScan
,作为实体在两个不同的包。 作为测试的嵌入式数据库,我使用H2。
schema.sql
其中包含两个CREATE SCHEMA IF NOT EXISTS
语句,如本问题所述 。 data.sql
文件。 问题是现在,那春天开机第一次执行schema.sql
,那么data.sql
并且在这之后休眠再次创建表,这最终导致空表。 为了解决这个问题,我尝试在application.properties
设置spring.jpa.hibernate.ddl-auto=none
。 但是,Hibernate现在开始切换命名策略,并将camelCase转换为slipne_case,这再次导致错误。 因此,我想这不是应该如何做。 我也尝试了spring.jpa.generate-ddl=false
,但这没有任何效果。 这怎么可能停用自动生成DDL(只使用schema.sql
和data.sql
),并在同一时间使用@DataJpaTest
?
非常感谢你!
spring:
autoconfigure:
exclude: org.springframework.boot.autoconfigure.security.SecurityAutoConfiguration
jackson:
serialization:
indent_output: true
datasource:
driver-class-name: org.hsqldb.jdbcDriver
generate-unique-name: true
jpa:
hibernate:
ddl-auto: none
show-sql: true
h2:
console:
enabled: false
liquibase:
change-log: classpath:/liquibase/db.changelog-master.xml
drop-first: true
contexts: QA
@Bean
LocalContainerEntityManagerFactoryBean entityManagerFactory(DataSource dataSource, Environment env) {
final LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
factory.setDataSource(dataSource);
factory.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
factory.setPackagesToScan("com.spring.web.demo.persistent.entity");
factory.setJpaProperties(jpaProperties(env));
return factory;
}
private Properties jpaProperties(Environment env) {
final Properties properties = new Properties();
properties.put("hibernate.dialect", env.getRequiredProperty("hibernate.dialect"));
//!!!: see here
properties.put("hibernate.hbm2ddl.auto", "none");
properties.put("hibernate.show_sql", env.getRequiredProperty("hibernate.show_sql"));
properties.put("hibernate.format_sql", false);
properties.put("hibernate.physical_naming_strategy", PhysicalNamingStrategyStandardImpl.class.getName());
properties.put("hibernate.generate_statistics", true);
properties.put("hibernate.cache.use_second_level_cache", true);
properties.put("hibernate.cache.use_query_cache", true);
properties.put("hibernate.cache.region.factory_class", "org.hibernate.cache.ehcache.EhCacheRegionFactory");
return properties;
}
注意, application.properies
或application.yaml
应该在test/resources
并且带有@Bean
的@Configuration
类应该由测试使用。
为了通过sql
-files进行测试,可以使用EmbeddedDataSource
我的github上有一些例子
您可以创建另一个application.properties并为测试目录下的文件配置文件。
对于其他问题,请在数据库创建后使用flywayflyway脚本,这是您的插入脚本自动运行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.