2

Liquibase has a servlet option to initialize the database. http://liquibase.org/manual/servlet_listener

Is there an example of this for Flyway? Or, better yet a working servlet?

Joel
  • 2,601
  • 4
  • 33
  • 44

1 Answers1

2

What you really want, is to run flyway.migrate() on startup. This can be accomplished through a variety of ways, Servlet Listeners being one of them.

There is no servlet listener included out of the box, but it's trivial to roll your own.

It should look something like this:

@WebListener
public class FlywayListener implements ServletContextListener {

    public void contextInitialized(ServletContextEvent sce) {
        Flyway flyway = new Flyway();
        flyway.setDataSource(...);
        flyway.migrate();
    }

    public void contextDestroyed(ServletContextEvent sce) {
    }
}

A class implementing the ServletContextListener interface is called before the first servlet (or filter) invocation and after the last. The @WebListener annotation is one way to inform your Servlet container of your intended listener. For more info, see this Oracle Tutorial and search Stack Overflow.

Community
  • 1
  • 1
Axel Fontaine
  • 34,542
  • 16
  • 106
  • 137
  • haven't gotten chance to integrate, when I do I'll post the web.xml I use. – Joel Dec 11 '12 at 22:26
  • my next question is where in the world does one obtain DataSource from JPA? – Joel Dec 11 '12 at 23:20
  • For more info on `ServletContextListener`, see [my Answer](http://stackoverflow.com/a/36588744/642706) to [Hook for my Vaadin web app starting and stopping?](http://stackoverflow.com/q/36588743/642706). ( [Vaadin](http://www.Vaadin.com/) is a Servlet framework; my Answer applies to any Servlet situation. ) The trick comes in trying to halt your web app if Flyway encounters a problem. See my Question, [Stop launch of web app from `ServletContextListener` method `contextInitialized`](http://stackoverflow.com/q/36611392/642706). The Servlet spec does not clearly provide for such interruption. – Basil Bourque May 15 '17 at 06:30