[英]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.