Spring Boot: Hibernate and Flyway boot order

前端 未结 6 668
一整个雨季
一整个雨季 2020-12-09 03:52

I have created Spring application. Pom xml is attached.

It has a config like this (below) and some db/migration/V1__init.sql for Flyway db migration tool.

It

6条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-09 04:05

    I had the same issue.

    I wanted my schema to be created by hibernate because of it's database independence. I already went through the trouble of figuring out a nice schema for my application in my jpa classes, I don't like repeating myself.

    But I want some data initialization to be done in a versioned manner which flyway is good at.

    Spring boot runs flyway migrations before hibernate. To change it I overrode the spring boot initializer to do nothing. Then I created a second initializer that runs after hibernate is done. All you need to do is add this configuration class:

    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);
        }
    
    
    }
    

    That code needs java 8, If you have java 7 or earlier, replace (f)->{} with an inner class that implements FlywayMigrationStrategy

    Of course you can do this in xml just as easily.

    Make sure to add this to your application.properties:

    flyway.baselineOnMigrate = true
    

提交回复
热议问题