Hey Spring Boot Team,

I already reported this in the spring-data-jpa repository (see https://github.com/spring-projects/spring-data-jpa/issues/3959), but was sent here. I'm facing a circular dependency problem using Flyway Java-based migrations. This issue has also been discussed in https://github.com/flyway/flyway/issues/1062#event-18796916491.

If you're initializing Flyway Java-based migrations as Spring Beans, they're injected into the Flyway instance using Spring's DI mechanism. This can be found in FlywayAutoConfiguration. Since the Java-based migrations are Spring Beans themselves, you can inject other beans. If those beans are somehow associated with JPA, the application fails on startup because a circular dependency between the EntityManagerFactory and Flyway is detected. This dependency between database initializing beans and dependent beans is documented here.

I've created a minimal example that shows this issue. Is this the desired behavior? In https://github.com/flyway/flyway/issues/1062 there is a suggested workaround, but it feels like missing the point having Java-based migrations as Spring beans and not being able to use the JPA layer out of the box.

Best Regards Leon

Comment From: wilkinsona

You can't use Flyway to both migrate the database that's used by JPA and use JPA during that migration. That would be true with or without Spring's involvement. How did you expect this to work from a JPA perspective?

Comment From: Leon116

Maybe I did not think this through. I assumed for each release first the schema changes are run by SQL migrations and the Java-based migrations are run at last only doing data changes, which is my actual use case. This ensures JPA always sees the release's final database schema. I pushed the branch test-jpa-bean-workaround using the workaround described in https://github.com/flyway/flyway/issues/1062 to the minimal example showing that using JPA during the Flyway migration is possible in that specific scenario.

If you want to use JPA in Java-based migration and do schema changes after in the same release, that would obviously not be possible, because Flyway does not migrate your code or something. The same applies, if you have a database and test data that is always rebuilt from scratch, e.g. a test environment or integration tests. In that case you have to find another way to somehow migrate your test data.

Maybe it's just my particular scenario, in which using JPA in Flyway Java-based migration would be useful and work quite well. But there's https://github.com/flyway/flyway/issues/1062 and I can also find some threads on stackoverflow regarding this issue. So maybe there are other people who would also profit from having a way to break the circular dependency and accept the limitations described above.