Tobias Erdle's Blog

Development Engineer working with different technologies. Former Jakarta MVC & Eclipse Krazo Committer. All views are my own.

Github: erdlet | E-Mail: blog (at) erdlet (punkt) de

Run Flyway migrations on Jakarta EE application startup

While Spring has integrated support for database migration tools like Flyway, in a plain Jakarta EE app everything needs to be bootstrapped by the developer. But thats easier than it seems, as the following code snippet shows:

{% highlight java %} @Startup @Singleton public class FlywayMigrator {

@Resource(lookup = "java:global/datasource-name)
private DataSource dataSource;

@PostConstruct
public void doMigration() {
    final Flyway flyway = Flyway.configure().dataSource(dataSource).load();

    flyway.migrate();
}

}

You simply need to implement a javax.ejb.Startup annotated bean (in the best case a javax.ejb.Singleton) and configure and run the Flyway migration there.

Using a ServletContextListener

If you don't want to use EJB implementing your web application, you can run FlyWay on startup with the help of a ServletContextListener. This needs a little bit more code than the example above, as the CDI Bean needs to be injected and executed within the listener. This step is necessary, as @ApplicationScoped beans are created lazy. The following code helps to run FlyWay on startup:

{% highlight java %} @ApplicationScoped public class FlywayMigrator {

@Resource(lookup = "java:global/datasource-name)
private DataSource dataSource;

public void doMigration() {
    final Flyway flyway = Flyway.configure().dataSource(dataSource).load();

    flyway.migrate();
}

}

@WebListener public class ApplicationBootstrapper implements ServletContextListener {

@Inject FlywayMigrator flywayMigrator;

@Override public void contextInitialized(final ServletContextEvent sce) { flywayMigrator.runMigration(); } }