CDI Extension for Flyway

Dominik Obermaier picture Dominik Obermaier · Jun 17, 2012 · Viewed 17k times · Source

I tried to run flyway in my application before hibernate is hooking in on my JBoss AS 7.1. I tried with an @javax.ejb.Startup annotation, but this gets executed AFTER Hibernate is initialized and the database scheme is checked.

So as far as I understand we can use a CDI Extension which hooks in before Hibernate is initialized. Is there some support for that out of the box for flyway? And if not, has anyone tried to do this before?

Answer

Dominik Obermaier picture Dominik Obermaier · Jul 19, 2012

Ok I finally found out how to do this: I had to use the Hibernate Integration API. This is the whole code I had to write:

public class FlywayIntegrator implements Integrator {

  @Override
  public void integrate(final Configuration configuration, final SessionFactoryImplementor sessionFactoryImplementor, final SessionFactoryServiceRegistry sessionFactoryServiceRegistry) {
    final Flyway flyway = new Flyway();

    flyway.setDataSource(....);
    flyway.migrate();
  }

  @Override
  public void integrate(final MetadataImplementor metadataImplementor, final SessionFactoryImplementor sessionFactoryImplementor, final SessionFactoryServiceRegistry sessionFactoryServiceRegistry) {
    //no-op
  }

  @Override
  public void disintegrate(final SessionFactoryImplementor sessionFactoryImplementor, final SessionFactoryServiceRegistry sessionFactoryServiceRegistry) {
    //no-op
  }
}

If anyone is interested in more details, I created a github project which demonstrates that: https://github.com/dobermai/Hibernate-Flyway-Integration