当前位置: 首页 > 知识库问答 >
问题:

Hibernate在使用Spring-Boot进行flyway迁移后无法验证内存中的h2数据库

司空均
2023-03-14

Hibernate无法验证由flyway迁移创建的数据库模式。(数据库迁移脚本是正确的)这是因为内存中的H2数据库吗?看起来hibernate和flyway连接到不同的数据库。

复制步骤:

用h2,flyway和jpa (hibernate)创建spring-boot项目。

应用属性:

spring.datasource.url=jdbc:h2:mem:flyway_db
spring.datasource.driver-class-name=org.h2.Driver
spring.jpa.hibernate.ddl-auto=validate
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.H2Dialect
spring.flyway.baseline-on-migrate=true
spring.flyway.url=jdbc:h2:mem:flyway_db

示例实体:

@Entity
@Table(name = "test_entity")
public class TestEntity {

    public int getId() {
        return id;
    }

    public void setId(final int id) {
        this.id = id;
    }

    public String getDesc() {
        return description;
    }

    public void setDesc(final String desc) {
        this.description = desc;
    }

    @Id
    private int id;
    private String description;
}

V1__init.sql脚本:

CREATE TABLE test_entity
(
    id INTEGER,
    description VARCHAR(255),
    PRIMARY KEY(id)
);

预期应用程序运行失败:完整日志:

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::                (v2.6.6)

2022-05-20 12:53:54.920  INFO 10104 --- [           main] flyway_hibernate_h2.test.Application     : Starting Application using Java 11.0.15 on cfe484487b08d045fbee329048f51788 with PID 10104 (/home/gitrow/eclipse-workspace-new/spring.flyway_hibernate_h2.test/target/classes started by gitrow in /home/gitrow/eclipse-workspace-new/spring.flyway_hibernate_h2.test)
2022-05-20 12:53:54.926  INFO 10104 --- [           main] flyway_hibernate_h2.test.Application     : No active profile set, falling back to 1 default profile: "default"
2022-05-20 12:53:55.594  INFO 10104 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode.
2022-05-20 12:53:55.613  INFO 10104 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 4 ms. Found 0 JPA repository interfaces.
2022-05-20 12:53:56.163  INFO 10104 --- [           main] o.f.c.internal.license.VersionPrinter    : Flyway Community Edition 8.0.5 by Redgate
2022-05-20 12:53:56.164  INFO 10104 --- [           main] o.f.c.i.database.base.BaseDatabaseType   : Database: jdbc:h2:mem:flyway_db (H2 1.4)
2022-05-20 12:53:56.241  INFO 10104 --- [           main] o.f.core.internal.command.DbValidate     : Successfully validated 1 migration (execution time 00:00.027s)
2022-05-20 12:53:56.263  INFO 10104 --- [           main] o.f.c.i.s.JdbcTableSchemaHistory         : Creating Schema History table "PUBLIC"."flyway_schema_history" ...
2022-05-20 12:53:56.337  INFO 10104 --- [           main] o.f.core.internal.command.DbMigrate      : Current version of schema "PUBLIC": << Empty Schema >>
2022-05-20 12:53:56.344  INFO 10104 --- [           main] o.f.core.internal.command.DbMigrate      : Migrating schema "PUBLIC" to version "1 - init"
2022-05-20 12:53:56.381  INFO 10104 --- [           main] o.f.core.internal.command.DbMigrate      : Successfully applied 1 migration to schema "PUBLIC", now at version v1 (execution time 00:00.054s)
2022-05-20 12:53:56.517  INFO 10104 --- [           main] o.hibernate.jpa.internal.util.LogHelper  : HHH000204: Processing PersistenceUnitInfo [name: default]
2022-05-20 12:53:56.558  INFO 10104 --- [           main] org.hibernate.Version                    : HHH000412: Hibernate ORM core version 5.6.7.Final
2022-05-20 12:53:56.736  INFO 10104 --- [           main] o.hibernate.annotations.common.Version   : HCANN000001: Hibernate Commons Annotations {5.1.2.Final}
2022-05-20 12:53:56.832  INFO 10104 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Starting...
2022-05-20 12:53:56.854  INFO 10104 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Start completed.
2022-05-20 12:53:56.874  INFO 10104 --- [           main] org.hibernate.dialect.Dialect            : HHH000400: Using dialect: org.hibernate.dialect.H2Dialect
2022-05-20 12:53:57.385 ERROR 10104 --- [           main] j.LocalContainerEntityManagerFactoryBean : Failed to initialize JPA EntityManagerFactory: [PersistenceUnit: default] Unable to build Hibernate SessionFactory; nested exception is org.hibernate.tool.schema.spi.SchemaManagementException: Schema-validation: missing table [test_entity]
2022-05-20 12:53:57.386  WARN 10104 --- [           main] s.c.a.AnnotationConfigApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory; nested exception is org.hibernate.tool.schema.spi.SchemaManagementException: Schema-validation: missing table [test_entity]
2022-05-20 12:53:57.386  INFO 10104 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Shutdown initiated...
2022-05-20 12:53:57.393  INFO 10104 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Shutdown completed.
2022-05-20 12:53:57.402  INFO 10104 --- [           main] ConditionEvaluationReportLoggingListener : 

Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2022-05-20 12:53:57.427 ERROR 10104 --- [           main] o.s.boot.SpringApplication               : Application run failed

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory; nested exception is org.hibernate.tool.schema.spi.SchemaManagementException: Schema-validation: missing table [test_entity]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1804) ~[spring-beans-5.3.18.jar:5.3.18]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:620) ~[spring-beans-5.3.18.jar:5.3.18]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:542) ~[spring-beans-5.3.18.jar:5.3.18]
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335) ~[spring-beans-5.3.18.jar:5.3.18]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-5.3.18.jar:5.3.18]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333) ~[spring-beans-5.3.18.jar:5.3.18]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208) ~[spring-beans-5.3.18.jar:5.3.18]
    at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1154) ~[spring-context-5.3.18.jar:5.3.18]
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:908) ~[spring-context-5.3.18.jar:5.3.18]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:583) ~[spring-context-5.3.18.jar:5.3.18]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:740) ~[spring-boot-2.6.6.jar:2.6.6]
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:415) ~[spring-boot-2.6.6.jar:2.6.6]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:303) ~[spring-boot-2.6.6.jar:2.6.6]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1312) ~[spring-boot-2.6.6.jar:2.6.6]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1301) ~[spring-boot-2.6.6.jar:2.6.6]
    at flyway_hibernate_h2.test.Application.main(Application.java:10) ~[classes/:na]
Caused by: javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory; nested exception is org.hibernate.tool.schema.spi.SchemaManagementException: Schema-validation: missing table [test_entity]
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:421) ~[spring-orm-5.3.18.jar:5.3.18]
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:396) ~[spring-orm-5.3.18.jar:5.3.18]
    at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.afterPropertiesSet(LocalContainerEntityManagerFactoryBean.java:341) ~[spring-orm-5.3.18.jar:5.3.18]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1863) ~[spring-beans-5.3.18.jar:5.3.18]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1800) ~[spring-beans-5.3.18.jar:5.3.18]
    ... 15 common frames omitted
Caused by: org.hibernate.tool.schema.spi.SchemaManagementException: Schema-validation: missing table [test_entity]
    at org.hibernate.tool.schema.internal.AbstractSchemaValidator.validateTable(AbstractSchemaValidator.java:129) ~[hibernate-core-5.6.7.Final.jar:5.6.7.Final]
    at org.hibernate.tool.schema.internal.GroupedSchemaValidatorImpl.validateTables(GroupedSchemaValidatorImpl.java:42) ~[hibernate-core-5.6.7.Final.jar:5.6.7.Final]
    at org.hibernate.tool.schema.internal.AbstractSchemaValidator.performValidation(AbstractSchemaValidator.java:97) ~[hibernate-core-5.6.7.Final.jar:5.6.7.Final]
    at org.hibernate.tool.schema.internal.AbstractSchemaValidator.doValidation(AbstractSchemaValidator.java:76) ~[hibernate-core-5.6.7.Final.jar:5.6.7.Final]
    at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.performDatabaseAction(SchemaManagementToolCoordinator.java:204) ~[hibernate-core-5.6.7.Final.jar:5.6.7.Final]
    at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.process(SchemaManagementToolCoordinator.java:85) ~[hibernate-core-5.6.7.Final.jar:5.6.7.Final]
    at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:335) ~[hibernate-core-5.6.7.Final.jar:5.6.7.Final]
    at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:471) ~[hibernate-core-5.6.7.Final.jar:5.6.7.Final]
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:1498) ~[hibernate-core-5.6.7.Final.jar:5.6.7.Final]
    at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:58) ~[spring-orm-5.3.18.jar:5.3.18]
    at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:365) ~[spring-orm-5.3.18.jar:5.3.18]
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:409) ~[spring-orm-5.3.18.jar:5.3.18]
    ... 19 common frames omitted

我尝试了:显式命名内存数据库,显式命名数据源和flyway的模式。

共有1个答案

彭飞虎
2023-03-14

正如问题下面的注释所指出的,可以通过从属性文件中删除属性spring.flyway.url来解决问题。

如果未设置该属性,则Spring Boot将使用主<code>DataSource</code>配置Flyway,如果存在,则使用<code>@FlywayDataSource注释的<code>数据源。属性<code>spring.flyway。url</code>存在以使用具体的连接字符串覆盖此选择html" target="_blank">过程。相关代码可在FlywayAutoConfiguration类中找到。

在H2的特殊情况下,覆盖连接字符串会导致一个问题,即H2数据库在事务后不会保持打开状态,除非连接字符串包含告诉它这样做的标志。这解释了问题中的观察结果,即Flyway对一个数据库运行,该数据库随后被关闭,然后Hibernate连接到一个全新的H2实例。

这遵循了Spring Boot的通常模式及其自动配置哲学。自动配置旨在不干涉工作,仅由类路径上的东西触发。因此,对于它的许多特性,不需要属性或代码来启用它们。

与此同时,Spring Boot只能使用合理的默认值或启发式方法来确定在什么情况下应该配置什么自动配置。因此,Spring Boot带有扩展点和标志,如果自动配置没有做正确的事情,可以很容易地退出。属性spring.flyway.url就是这些标志之一。

 类似资料:
  • 我正在使用Flyway更新DB模式。当前,模式的最新版本是3(最新的迁移文件名为)。 我是否正确理解了参数,还是遗漏了什么? 注意:我知道自Spring Boot2以来,参数名称空间已经更改为,但我使用的是Spring Boot1,所以这不是问题。

  • 我正在尝试使用Flyway运行数据库迁移脚本。我有两个SQL脚本和一个Java脚本正在尝试运行。当我跑步的时候/gradlew flywayMigrate或gradle flywayMigrate它只接受SQL脚本,而不接受Java脚本 我的项目设置如下: database_migrations 我尝试了多种解决方案来让java脚本运行,例如指定,但这只会导致此输出。我尝试过将其移动到其他包。我尝

  • 我使用Hibernate将Roo生成的SpringMVC应用程序连接到PostgreSQL。我试图将Flyway1.6作为一个bean集成到Spring应用程序上下文中。“有什么东西阻止”迁移的执行,我在上下文初始化时遇到了由Hibernate元数据验证引起的错误。使用Flyway 1.6 Maven插件(clean、init、migrate)执行迁移没有问题。 Flyway 1.5(早期版本)的

  • 问题内容: 我了解到使用Java进行flywaydb迁移可与JDBC连接一起使用,并且还可以通过SpringTemplate进行spring支持,但是flyway不适用于DAO。 对于具有更多关系的表/实体,使用DAO而不是sql进行迁移使工作变得更加容易。 是否有解决方案或解决方法来解决此问题? 问题答案: 首先,Flyway拥有自己的事务管理系统,并且不使用Spring事务处理。 如果您的DA

  • 我使用h2db进行测试,使用hibernate自动创建表,但希望flyway在数据库中插入脚本。所以,我的飞行路线没有创建脚本。 首先,我不确定这是否可能。但是当我使用一些插入脚本时,我的测试失败了,因为flyway无法插入记录,抱怨表格不存在。 似乎在h2创建表之前,它就已经在尝试运行脚本了。 我正在使用Spring靴来调用飞行路线。所以,我只需要这个依赖项和一个数据库。类路径中的migarat

  • 我试图在Spring Boot应用程序中使用Flyway对嵌入式H2数据库进行迁移演示。 应用程序.属性 迁移-db/migration下的脚本(V2__create_shipwreck.sql) 信息7284---[main]o.f.c.i.s.jdbctableSchemaHistory:创建架构历史记录表:“public”.“flyway_schema_history” 信息7284---[