Skip to content

Connect with Java

Connect a Java application to a Managed PostgreSQL service with the PostgreSQL JDBC driver (pgjdbc), with TLS certificate verification and credentials read from the environment.

Prerequisites

You need:

The service accepts TLS connections only. The SSL modes are explained in Connect with psql.

Add pgjdbc to your build. With Maven:

<dependency>
  <groupId>org.postgresql</groupId>
  <artifactId>postgresql</artifactId>
  <version>42.7.14</version>
</dependency>

With Gradle:

implementation 'org.postgresql:postgresql:42.7.14'

pgjdbc reads the PEM CA certificate given in sslrootcert directly: no Java truststore is needed.

Retrieve the Credentials and the CA Certificate

Export the connection fields, and save the CA certificate where the application can read it:

eval "$(exo dbaas show SERVICE_NAME -z ZONE -O json | jq -r '.pg.uri_params | "export PGHOST=\(.host) PGPORT=\(.port) PGDATABASE=\(.dbname) PGUSER=\(.user)"')"
export PGPASSWORD="$(exo dbaas user reveal-secrets SERVICE_NAME avnadmin -z ZONE -O json | jq -r .password)"
exo dbaas ca-certificate -z ZONE > ca.pem
export PGSSLROOTCERT="$PWD/ca.pem"

Parameters:

  • SERVICE_NAME: name of your Managed PostgreSQL service, for example my-postgresql.
  • ZONE: Exoscale zone the service runs in, for example ch-gva-2.

The JSON output of exo dbaas show does not include the password, which is why the second command reads it with exo dbaas user reveal-secrets.

Connect

Save the following as PostgresqlExample.java:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public class PostgresqlExample {

  private static String required(String name) {
    String value = System.getenv(name);
    if (value == null || value.isEmpty()) {
      throw new IllegalStateException("Environment variable " + name + " is not set");
    }
    return value;
  }

  private static Connection connect() throws SQLException {
    String url = String.format(
        "jdbc:postgresql://%s:%s/%s",
        required("PGHOST"), required("PGPORT"), required("PGDATABASE"));

    Properties props = new Properties();
    props.setProperty("user", required("PGUSER"));
    props.setProperty("password", required("PGPASSWORD"));
    props.setProperty("sslmode", "verify-full");
    props.setProperty("sslrootcert", required("PGSSLROOTCERT"));
    props.setProperty("connectTimeout", "10");
    props.setProperty("ApplicationName", "exoscale-java-sample");

    return DriverManager.getConnection(url, props);
  }

  public static void main(String[] args) throws SQLException {
    try (Connection connection = connect();
         Statement statement = connection.createStatement()) {

      try (ResultSet rs =
               statement.executeQuery("SELECT version(), current_database(), current_user")) {
        while (rs.next()) {
          System.out.println("server:   " + rs.getString(1));
          System.out.println("database: " + rs.getString(2));
          System.out.println("user:     " + rs.getString(3));
        }
      }

      try (ResultSet rs = statement.executeQuery(
               "SELECT version, cipher FROM pg_stat_ssl WHERE pid = pg_backend_pid()")) {
        while (rs.next()) {
          System.out.println("tls:      " + rs.getString(1) + " " + rs.getString(2));
        }
      }
    }
  }
}

Download postgresql-42.7.14.jar from Maven Central, then compile and run the sample:

javac -cp postgresql-42.7.14.jar PostgresqlExample.java
java -cp postgresql-42.7.14.jar:. PostgresqlExample

On Windows, use ; instead of : as the classpath separator.

The last line shows the TLS version and cipher of the session. If PGSSLROOTCERT points to the wrong certificate, the connection fails with SSL error: (certificate_unknown) PKIX path building failed.

Passing the credentials in a Properties object rather than in the JDBC URL avoids percent-encoding the password and keeps it out of any log line that prints the URL.

The JDBC URL Form

To configure a connection pool or an application server datasource with a single URL, use:

jdbc:postgresql://HOST:PORT/DATABASE_NAME?sslmode=verify-full&sslrootcert=CA_PATH

Parameters:

  • HOST: service hostname, the PGHOST value above.
  • PORT: service port, the PGPORT value above. It is assigned per service and is not 5432.
  • DATABASE_NAME: database to connect to, defaultdb by default.
  • CA_PATH: absolute path to the CA certificate retrieved above.

The username and password are supplied separately, by the datasource or by DriverManager.getConnection(url, user, password).

Warning

Without an explicit sslmode, pgjdbc uses prefer: the connection is encrypted, but the server certificate is not verified. Always set sslmode=verify-full.

Use a Connection Pool

A server application should hold a bounded pool rather than open a connection per request. With HikariCP:

HikariConfig config = new HikariConfig();
config.setJdbcUrl(String.format("jdbc:postgresql://%s:%s/%s",
    System.getenv("PGHOST"), System.getenv("PGPORT"), System.getenv("PGDATABASE")));
config.setUsername(System.getenv("PGUSER"));
config.setPassword(System.getenv("PGPASSWORD"));
config.addDataSourceProperty("sslmode", "verify-full");
config.addDataSourceProperty("sslrootcert", System.getenv("PGSSLROOTCERT"));
config.setMaximumPoolSize(10);

HikariDataSource dataSource = new HikariDataSource(config);

Read the server limit with SHOW max_connections; and keep the sum of maximumPoolSize across all your application instances below it. To share a small number of server connections between many application instances, use a server-side pool: see Manage Connection Pools.

Related Pages

Last updated on