LanguageGB
Databases

Connect a Java app to PostgreSQL

JDBC needs a different connection string from the one in the other guides, plus two settings that only bite you later.

What this covers

Java does not use the DATABASE_URL format shown elsewhere in these guides — JDBC has its own. Reaching the database from a Java VM also goes over our TLS endpoint rather than the internal one, so there is something to switch on first. And two parameters in the URL matter far more than they look.

Before you start

Create the database and copy its name, user and password. Add the PostgreSQL JDBC driver to your build — for Spring Boot that is org.postgresql:postgresql.

How to do it

  1. Turn on external access for the database, on its Connection tab. Your Java VM is your own machine with your own root on it, so it reaches the database over the same TLS endpoint your laptop would, not the internal one we keep for infrastructure we operate ourselves. Apps on App Deployment do not need this step; Java VMs do.
  2. Build the JDBC URL yourself rather than copying DATABASE_URL: jdbc:postgresql://db.cmcloudhosting.com:5432/yourdatabase?sslmode=require&prepareThreshold=0
  3. Leave sslmode=require in place. The endpoint refuses unencrypted connections, and without it you get FATAL: SSL required.
  4. Leave prepareThreshold=0 in place too. Your connection goes through a pooler that reuses server connections between transactions. The JDBC driver switches to server-side prepared statements after running the same query five times, and those do not survive the reuse. Leave it out and you get "prepared statement S_1 does not exist" once you have real traffic — not on your first request, which is exactly what makes it hard to find.
  5. Read the URL, user and password from environment variables. In Spring Boot they map to spring.datasource.url, spring.datasource.username and spring.datasource.password.
  6. Keep the connection pool small — eight is plenty. With this kind of pooling a bigger pool holds slots without giving you more concurrency.
  7. Let your migration tool create the schema. Flyway and Liquibase both run at startup, and the database arrives empty.
  8. Test the connection before you deploy: psql "host=db.cmcloudhosting.com port=5432 dbname=yourdatabase user=youruser sslmode=require" -c "select version();". If that fails, the problem is not in your application. Install the client with apt-get install postgresql-client if it is missing.
  9. Start your app, then open the Tables tab in the portal to confirm your migrations ran and rows are landing.

What our team checks

We can confirm the database exists, that external access is on, that the endpoint is reachable and that TLS is negotiating. We cannot see inside your application, so send us the exact error text if it will not connect.

Next step

Turn on external access, set the three variables, and run the psql check. Once that works, start your app and look at the Tables tab.

Contact Support