Spring非Boot模块集成测试时Hibernate无法基于@Entity自动建表
修复方案
遗漏配置项补充
1. 修正基础配置错误
首先修正测试类上的注解拼写错误:@ConstextConfiguration应为@ContextConfiguration,拼写错误会直接导致上下文配置加载失败。
2. 完善application-test.yml配置
补充H2数据源及Hibernate方言配置,让Spring可以正确识别数据库类型、初始化内存实例:
spring: datasource: driver-class-name: org.h2.Driver url: jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1 username: sa password: jpa: hibernate: ddl-auto: create database-platform: org.hibernate.dialect.H2Dialect show-sql: true generate-ddl: true
3. 启用JPA相关能力
因为你没有使用@SpringBootTest,Spring Boot的JPA、数据源自动配置默认不会生效,有两种方案可选:
方案A:手动导入自动配置类(推荐,代码量少)
如果你的项目引入了Spring Boot自动配置依赖,直接在测试内部的配置类上导入对应自动配置类即可:
@Configuration @ComponentScan("base.module.package") @Import({ DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class, JpaRepositoriesAutoConfiguration.class }) static class TestConfiguration { // 仅测试用的Bean定义 }
同时在测试类上添加@EnableJpaRepositories("your.repository.package.path")注解,扫描你的Repository接口所在包。
方案B:纯Spring手动注册核心Bean
如果没有引入Spring Boot自动配置依赖,直接在测试配置类中手动定义JPA核心Bean:
@Configuration @ComponentScan("base.module.package") @EnableJpaRepositories("your.repository.package.path") static class TestConfiguration { @Bean public DataSource dataSource() { return new EmbeddedDatabaseBuilder() .setType(EmbeddedDatabaseType.H2) .build(); } @Bean public LocalContainerEntityManagerFactoryBean entityManagerFactory(DataSource dataSource) { HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); vendorAdapter.setShowSql(true); vendorAdapter.setDatabase(Database.H2); vendorAdapter.setGenerateDdl(true); LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean(); factory.setJpaVendorAdapter(vendorAdapter); factory.setPackagesToScan("path.to.package.where.parameter.entity.resides"); factory.setDataSource(dataSource); Properties jpaProperties = new Properties(); jpaProperties.put("hibernate.hbm2ddl.auto", "create"); factory.setJpaProperties(jpaProperties); return factory; } @Bean public PlatformTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) { return new JpaTransactionManager(entityManagerFactory); } }
调试切入点
- 检查测试启动时控制台有没有输出Hibernate的建表SQL,没有输出说明Entity扫描失败或Hibernate配置未生效,优先核对
@EntityScan的包路径是否正确 - 断点查看Spring上下文中是否存在
DataSource、EntityManagerFactory实例,实例类型是否为H2对应的实现,不存在则说明数据源配置未加载 - 断点定位到
org.hibernate.tool.hbm2ddl.SchemaExport#execute方法,查看是否触发了建表逻辑,未触发则说明Hibernate的DDL配置未生效 - 若建表SQL已经输出还是提示表不存在,检查H2连接URL的
DB_CLOSE_DELAY=-1参数是否配置,该参数保证内存库在连接断开后不会被销毁
内容的提问来源于stack exchange,提问作者mr.nothing
相关产品推荐
相关产品推荐

