在 flyway 迁移脚本之前执行 JPA 表创建
Posted
技术标签:
【中文标题】在 flyway 迁移脚本之前执行 JPA 表创建【英文标题】:Execute JPA table creation before flyway migration script 【发布时间】:2019-01-09 06:41:11 【问题描述】:我想使用这个 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先创建表,然后flyway执行迁移脚本?
【问题讨论】:
【参考方案1】: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的回答你会得到详细信息。
【讨论】:
【参考方案2】:为了避免循环依赖,这样写:
@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答案
【讨论】:
以上是关于在 flyway 迁移脚本之前执行 JPA 表创建的主要内容,如果未能解决你的问题,请参考以下文章