Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CDI Extension for Flyway

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?

like image 451
Dominik Obermaier Avatar asked Jun 17 '12 13:06

Dominik Obermaier


2 Answers

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

like image 83
Dominik Obermaier Avatar answered Nov 08 '22 10:11

Dominik Obermaier


CDI defines its own lifecycle which is executed when an applications starts / stops. (Shouldn't you know about it already: This is a good place to learn about the basic mechanism.)

The problem - to my best knowledge - is that the Hibernate initialization process is not directly linked to the CDI startup. This means that I'm not sure if its safe to rely on a relation between Hibernate & CDI "events". There is certainly nothing like a CDI-Event HibernateInitialized.

Having said this, I'd give it a try :) You should implement a simple extension that hooks up at BeforeBeanDiscovery, which is as early as it gets.

This online presentation gives an overview about the different CDI events and their order. It's in German, unfortunately.

like image 1
Jan Groth Avatar answered Nov 08 '22 09:11

Jan Groth