Search code examples
javapostgresqlmavenjdbcjar

No suitable driver found when including the needed drivers with maven-assembly-plugin


I have a very small too that works with a PostgreSQL DB and it would be very convenient to use it as a single jar. So indeed I've tried using the maven-assembly-plugin like so:

<artifactId>maven-assembly-plugin</artifactId>
<version>2.3</version>
<configuration>
    <archive>
        <manifest>
            <mainClass>pack.name.MainClass</mainClass>
        </manifest>
    </archive>
    <descriptorRefs>
        <descriptorRef>jar-with-dependencies</descriptorRef>
    </descriptorRefs>
</configuration>

And it works perfectly fine, I can see all the files I require added to the jar file, including the driver's files, but when I'm trying to run it I get a:

java.sql.SQLException: No suitable driver found for jdbc:postgresql://<ip>:5432/dbname

I have this:

<dependencies>
    <dependency>
        <groupId>com.oracle</groupId>
        <artifactId>ojdbc6</artifactId>
        <version>11.2.0.3</version>
    </dependency> 
    <dependency>
        <groupId>postgresql</groupId>
        <artifactId>postgresql</artifactId>
        <version>9.1-901-1.jdbc4</version>
    </dependency>

In the dependencies and the URL is exactly as I wrote above (except the censored address). What am I missing?


Solution

  • If you don't use Class.forName(...) to load the driver manually, then I think you faced an infamous problem with maven-assembly-plugin - it overwrites files with the same name when they come from different jars.

    In your case JDBC driver discovery mechanism relies on a file named /META-INF/services/java.sql.Driver, and you have at least two jars containing such a file in your dependencies (Oracle and Postgres drivers), therefore one of them is lost after running maven-assembly-plugin.

    You can use maven-shade-plugin instead of maven-assembly-plugin to merge these files correcly, as described here.

    Alternatively, you can use Class.forName(...) to sidestep the failing autodiscovery mechanism.