在Flyway迁移脚本之前执行JPA表创建

时间:2018-08-01 15:52:59

标签: spring spring-boot jpa flyway

我想将此Spring属性文件用于数据库配置。

spring.jmx.enabled=false
spring.datasource.jndi-name=java:/global/production
spring.datasource.driver-class-name=org.mariadb.jdbc.Driver
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MariaDBDialect
spring.jpa.show-sql = true
spring.jpa.hibernate.ddl-auto = update
request.limit=300000
spring.flyway.baselineOnMigrate = true
spring.flyway.locations=classpath:/db/migration

代码运行良好,但不幸的是,在删除所有表后数据库为空时,由于首先执行迁移脚本,因此我收到SQL错误。

如何首先配置JPA以创建表,然后配置运行迁移脚本的途径?

2 个答案:

答案 0 :(得分:2)

Flyway迁移在休眠执行之前运行。您可以通过查看启动顺序来完成。为此,您需要添加以下配置类:

import org.flywaydb.core.Flyway;
import 
org.springframework.boot.autoconfigure.flyway.FlywayMigrationInitializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;

@Configuration
public class MigrationConfiguration {


/**
 * Override default flyway initializer to do nothing
 */
@Bean
FlywayMigrationInitializer flywayInitializer(Flyway flyway) {
    return new FlywayMigrationInitializer(flyway, (f) ->{} );
}


/**
 * Create a second flyway initializer to run after jpa has created the schema
 */
@Bean
@DependsOn("entityManagerFactory")
FlywayMigrationInitializer delayedFlywayInitializer(Flyway flyway) {
    return new FlywayMigrationInitializer(flyway, null);
}


}

看看this的答案,您会获得详细信息。

答案 1 :(得分:0)

为了避免循环依赖,可以这样写:

@Configuration
public class FlywayConfig {

    @Bean
    FlywayMigrationInitializer flywayInitializer(Flyway flyway) {
        return new FlywayMigrationInitializer(flyway, (f) -> {
        });
    }

    static class Dummy {
    }

    @Bean
    @DependsOn("entityManagerFactory")
    Dummy delayedFlywayInitializer(Flyway flyway, FlywayProperties flywayProperties) {
        if (flywayProperties.isEnabled())
            flyway.migrate();
        return new Dummy();
    }
}

灵感来自this答案