繁体   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