How to Deploy Spring on Platform.sh with JPA
Back to home
On this page
To activate JPA and then have it accessed by the Spring application already configured for Platform.sh, it is necessary to modify two files.
Note
This guide only covers the addition of a service configuration to an existing Spring project already configured to deploy on Platform.sh. Please see the deployment guide for more detailed instructions for setting up app containers and initial projects.
1. Add a SQL database service
In your service configuration, include a SQL database service with a valid supported version to find a valid version. For PostgreSQL that would look like:
postgresql:
type: postgresql:16
disk: 256
2. Grant access to the service through a relationship
To access the new service, set a relationship
in your app configuration.
relationships:
postgresql: "postgresql:postgresql"
3. Export connection credentials to the environment
Connection credentials for services are exposed to the application container through the PLATFORM_RELATIONSHIPS
environment variable from the deploy hook onward. Since this variable is a base64 encoded JSON object of all of your project’s services, you’ll likely want a clean way to extract the information specific to the database into it’s own environment variables that can be used by Spring. On Platform.sh, custom environment variables can be defined programmatically in a .environment
file using jq
to do just that:
export DB_PORT=`echo $PLATFORM_RELATIONSHIPS|base64 -d|jq -r ".postgresdatabase[0].port"`
export HOST=`echo $PLATFORM_RELATIONSHIPS|base64 -d|jq -r ".postgresdatabase[0].host"`
export DATABASE=`echo $PLATFORM_RELATIONSHIPS|base64 -d|jq -r ".postgresdatabase[0].path"`
export SPRING_DATASOURCE_URL="jdbc:mysql://${HOST}:${DB_PORT}/${DATABASE}"
export SPRING_DATASOURCE_USERNAME=`echo $PLATFORM_RELATIONSHIPS|base64 -d|jq -r ".postgresdatabase[0].username"`
export SPRING_DATASOURCE_PASSWORD=`echo $PLATFORM_RELATIONSHIPS|base64 -d|jq -r ".postgresdatabase[0].password"`
export JAVA_OPTS="-Xmx$(jq .info.limits.memory /run/config.json)m -XX:+ExitOnOutOfMemoryError"
Tip
For access to more credentials options, check Spring common application properties and binding from environment variables.
4. Connect to the service
Commit that code and push. The specified cluster now always points to the PostgreSQL or any SQL service that you wish.