Flyway/SpringBoot+H2内存数据库集成问题:单元测试失败排查
问题:单元测试中Flyway配置无效导致表不存在错误
错误信息
org.springframework.jdbc.BadSqlGrammarException: PreparedStatementCallback; 错误SQL语法 [INSERT INTO merchant_rating_detail (order_id, shop_id, user_id, rating, created_datetime, feedback_ids) VALUES(?, ?, ?, ?, ?, ?);]; 嵌套异常为 org.h2.jdbc.JdbcSQLSyntaxErrorException: 表"merchant_rating_detail"不存在(数据库为空); SQL语句: INSERT INTO merchant_rating_detail (order_id, shop_id, user_id, rating, created_datetime, feedback_ids) VALUES(?, ?, ?, ?, ?, ?); [42104-214]
配置信息
# Flyway spring.flyway.enabled= false # H2 spring.datasource.url=jdbc:h2:mem:testdb;DATABASE_TO_UPPER=false;DB_CLOSE_ON_EXIT=FALSE spring.datasource.driverClassName=org.h2.Driver spring.datasource.username=sa spring.datasource.password=password spring.jpa.database-platform=org.hibernate.dialect.H2Dialect spring.jpa.defer-datasource-initialization=true
问题描述
我正尝试让单元测试通过,但不知如何操作。请问如何正确实现Flyway?我已尝试添加;DATABASE_TO_UPPER=false;DB_CLOSE_ON_EXIT=FALSE和spring.jpa.defer-datasource-initialization=true,但均无效。
解决方案
启用Flyway
配置中spring.flyway.enabled= false直接禁用了Flyway,这是核心问题。要让Flyway执行数据库迁移,必须将其改为:spring.flyway.enabled= true规范迁移脚本的位置与命名
Flyway默认扫描classpath:db/migration目录,脚本命名必须遵循V<版本号>__<描述>.sql格式(例如V1__create_merchant_rating_detail_table.sql)。若脚本存放在自定义路径,需通过参数指定:spring.flyway.locations=classpath:your/custom/migration/path优化H2数据库配置
在H2连接URL中添加DB_CLOSE_DELAY=-1,避免内存数据库因连接关闭被销毁:spring.datasource.url=jdbc:h2:mem:testdb;DATABASE_TO_UPPER=false;DB_CLOSE_ON_EXIT=FALSE;DB_CLOSE_DELAY=-1协调Flyway与JPA的初始化顺序
建议将JPA的DDL自动生成功能关闭,完全依赖Flyway管理表结构,防止冲突:spring.jpa.hibernate.ddl-auto=none若需要保留JPA的初始化逻辑,
spring.jpa.defer-datasource-initialization=true参数可以保留,它会延迟JPA初始化直到Flyway完成迁移。验证迁移脚本的正确性
确保merchant_rating_detail表的创建脚本包含所有所需字段,示例如下:CREATE TABLE merchant_rating_detail ( order_id BIGINT NOT NULL, shop_id BIGINT NOT NULL, user_id BIGINT NOT NULL, rating INT NOT NULL, created_datetime TIMESTAMP NOT NULL, feedback_ids VARCHAR(255), PRIMARY KEY (order_id) -- 根据实际业务调整主键 );
内容的提问来源于stack exchange,提问作者Dang
相关产品推荐
相关产品推荐

