簡體   English   中英

沒有DDL生成的Spring Boot @DataJpaTest

[英]Spring Boot @DataJpaTest without ddl generation

我在兩個數據庫中都有帶MySQL的表,並想用SpringBoot(1.5.6.RELEASE)和JPA編寫測試。 對於這一點,我用的是@DataJpaTest連同@EntityScan ,作為實體在兩個不同的包。 作為測試的嵌入式數據庫,我使用H2。

  1. 我的第一個問題是,Spring Boot引發了一個異常,即找不到架構,因此我創建了一個schema.sql其中包含兩個CREATE SCHEMA IF NOT EXISTS語句,如本問題所述
  2. 但是,我還想插入一些測試數據並添加一個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.sqldata.sql ),並在同一時間使用@DataJpaTest

非常感謝你!

解決方案1:屬性/ YAML文件

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

解決方案2:覆蓋@Bean

@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.properiesapplication.yaml應該在test/resources並且帶有@Bean@Configuration類應該由測試使用。

為了通過sql -files進行測試,可以使用EmbeddedDataSource

我的github上有一些例子

您可以創建另一個application.properties並為測試目錄下的文件配置文件。

對於其他問題,請在數據庫創建后使用flywayflyway腳本,這是您的插入腳本自動運行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM