Search code examples
javapostgresqljdbcpg-jdbc

Java 9 JDBC setup


The problem

I'm currently working with Java 9 and its module system and want to connect to my PostgreSQL database via JDBC.

The problem is that I could not find any information on its setup with Java 9 and it's module system but only for Java 8 and older.

The question

How can I properly setup JDBC and its driver using the java module system?


Solution

  • The jar must be on the classpath at runtime. For compilation you do not need the jar.

    If the Postgresql driver is modularized already it would would work with the uses/provides mechanism for runtime:

    The java JRE:

    module java.sql {
       uses java.sql.Driver;
       exports java.sql;
    }
    

    The driver then should have something like this in module-info:

    module org.postgresql {
       requires java.sql;
       provides java.sql.Driver with org.postgresql.Driver;
    }
    

    And the normal ServiceLoader would discover the driver automatically.

    Class.forName("org.postgresql.Driver"); generally is not needed, just in some JavaEE applications where there is some class loader juggling.