关于java:Flyway和Spring Boot集成

Flyway and Spring Boot integration

我试图将Flyway与Hibernate和Spring JPA集成到Spring Boot项目中进行迁移。我收到以下异常:

1
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'flyway' defined in class path resource [org/springframework/boot/autoconfigure/flyway/FlywayAutoConfiguration$FlywayConfiguration.class]: Invocation of init method failed; nested exception is org.flywaydb.core.api.FlywayException: Found non-empty schema"PUBLIC" without metadata table! Use init() or set initOnMigrate to true to initialize the metadata table.

我的pom.xml看起来像这样:

1
2
3
4
5
<dependency>
  <groupId>org.flywaydb</groupId>
  flyway-core</artifactId>
  <version>3.2</version>
</dependency>

我正在使用Hibernate和一个用于postgres(开发阶段)和h2(本地)的配置Java文件。签名看起来像这样:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
  @Bean(initMethod ="migrate")
  public Flyway flyway() {
    Flyway fly = new Flyway();
    fly.clean();
    fly.init();
    //flyway.setInitOnMigrate(true);
    fly.setSchemas("SBA_DIALOG");
    //flyway.setLocations("filesystem:src/main/resources/db/migration");
    fly.setDataSource(this.dataSource());
    fly.migrate();
    return fly;
  }
@Bean(name ="sbaEntityManagerFactory") @DependsOn("flyway")
  public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
...

我在此问题中找不到关于我的问题的任何信息。
有人可以帮忙吗?


Spring-Boot本身具有执行此操作的能力。
只需添加flyway作为对项目的依赖项,spring-boot就会选择它。
服务启动时,将开始Flyway迁移。

如果数据库中已经有一些表,请添加:

1
spring.flyway.baselineOnMigrate = true

当发现某些表已经存在时,请在属性文件中使用

保持飞行路线平稳。 ;-)

Flyway应该获取您的数据源。例如,如果您需要其他用户或类似的飞行路线用户,则可以设置以下属性:

1
2
3
spring.flyway.url: jdbc:postgresql://${db.host}/${db.name}
spring.flyway.user: MYUSER
spring.flyway.password: MYPWD

(当然要添加您的值!您可以使用SPEL来引用其他属性)

更新

一个警告:如果使用群集数据库,则可能会遇到以下问题:多个实例同时启动,请尝试同时执行更新。当表锁不起作用时,这是一个问题,这是使用集群式mariaDB发生的。


对于任何想用Java代码解决它的人,都可以使用:

1
fly.setBaselineOnMigrate(true);

编辑(22-09-2020)

另一个解决方案也是:

1
2
3
4
spring:
  flyway:
    baselineOnMigrate: true
    validateOnMigrate: false