Search code examples
javajakarta-eestrutsjndiliquibase

Datasource for Liquibase as a Servlet Listener


I'm starting to configure Liquibase in my web.xml file, but I don't understand what the datasource attribute refers to:

<context-param>
  <param-name>liquibase.datasource</param-name>
  <param-value>java:comp/env/jdbc/default</param-value>
</context-param>

The documentation says it is a JNDI datasource, but I'm using Struts, not Spring, and have my connection details in different properties files (e.g. hibernate.dev.properties, hibernate.test.properties) which I load programatically depending on the current environment:

Configuration hibernateConfig = new Configuration();
hibernateConfig.addProperties("com/env.specific.properties");

To be honest, I don't have any idea of what is or how to use JNDI.

What should I write in that specific context-param value? Is there any way to do something similar to what I do with hibernate?

I am using Tomcat 6.0, in case that may help.


Solution

  • The property liquibase.datasource refers to the JNDI name of a DataSource object in your webapp's JNDI directory, as documented in the Liquibase manual.

    Since you are not using JNDI, you cannot use the default Servlet listener LiquibaseServletListener provided by Liquibase. I assume you are creating JDBC resources directly, e.g. within your web application. You probably have a C3P0 DataSource connection pool somewhere or access to the underlying JDBC Connection in some way.

    If this is the case, you could roll your own initializing and inject the JDBC Connection into Liquibase as follows:

    DataSource dataSource = ... // get from Hibernate somehow
    Connection connection = dataSource.getConnection();
    JdbcConnection liquibaseConnection = new JdbcConnection(connection);
    Liquibase liquibase = new Liquibase("mychangelog.xml",...,liquibaseConnection);
    liquibase.update("");
    

    This code snippet is not tested, but should be s.th. like that. You may add this in your own Servlet Context Initializer listener or in your app-specific code - any place where you have the Hibernate configuration at hand and can retrieve the DataSource. As a start, have a look into the sources of liquibase.servlet.LiquibaseServletListener how to do that.