Search code examples
javamavenosgiderbyapache-felix

How to use Derby Client in Felix?


I want to run Derby Client from within an OSGi bundle. The bundle gets built by Maven so I added a dependency to org.apache.derby:derbyclient. At runtime I get the following exception: java.sql.SQLException: No suitable driver found for jdbc:derby://localhost:1527/testdb.

Interestingly the whole thing works when I use the embedded driver and a dependency to org.apache.derby.derby. I just don't see the difference between those two.

What am I doing wrong and how can I fix it?

Some tidbits:

  1. After some advice I found on the Internet I set the following OSGi header: DynamicImport-Package: *. This fixed problems with the embedded driver but the client still fails.
  2. The version of Derby I use is 10.7.1.1 which should be OSGi enabled (at least it has OSGi headers).

Solution

  • Okay, although not even half an hour passed since I asked the question I found a solution. I don't know how clean it is but it seems to get the job done:

    ClassLoader ctxtCl = Thread.currentThread().getContextClassLoader();
    try {
        Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
    
        try {
            Class.forName("org.apache.derby.jdbc.ClientDriver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    
        dbConnection = DriverManager.getConnection("jdbc:derby://localhost:1527/testdb");
    } catch (SQLException e) {
        /* log, etc. */
    } finally {
        Thread.currentThread().setContextClassLoader(ctxtCl);
    }