Integrate Spanner with Spring Data JPA (PostgreSQL dialect)

Spring Data JPA, part of the larger Spring Data family, makes it easier to implement JPA based repositories. Spring Data JPA supports PostgreSQL and a wide range of other database systems. It adds an abstraction layer between your application and your database that makes your application easier to port from one database system to another.

Set up Spring Data JPA for Spanner PostgreSQL-dialect databases

You can integrate Spanner PostgreSQL-dialect databases with Spring Data JPA using the standard PostgreSQL Hibernate dialect and PGAdapter.

To see an example, refer to the full working sample application on GitHub.


In your project, add Apache Maven dependencies for Spring Data JPA, the PostgreSQL JDBC driver, and PGAdapter.

    <!-- Spring Data JPA -->
    <!-- Add the PostgreSQL JDBC driver -->
    <!-- Add PGAdapter as a dependency, so we can start it in-process -->

Start PGAdapter in-process

Add the following method to your application to start PGAdapter directly from your Java application. PGAdapter runs in the same JVM as your application, and the application connects to PGAdapter on localhost:port.

  /** Starts PGAdapter in-process and returns a reference to the server. */
  static ProxyServer startPGAdapter() {
    // Start PGAdapter using the default credentials of the runtime environment on port 9432.
    OptionsMetadata options = OptionsMetadata.newBuilder().setPort(9432).build();
    ProxyServer server = new ProxyServer(options);

    return server;


Configure to use the PostgreSQL Hibernate Dialect and the PostgreSQL JDBC Driver. Configure the PostgreSQL JDBC Driver to connect to a PostgreSQL-dialect database through PGAdapter.

# The example uses the standard PostgreSQL Hibernate dialect.

# Defining these properties here makes it a bit easier to build the connection string.
# Change these to match your Cloud Spanner PostgreSQL-dialect database.
# This setting ensures that PGAdapter automatically commits the current transaction if it encounters
# a DDL statement in a read/write transaction, and then executes the DDL statements as a single DDL
# batch. 

# This is the connection string to PGAdapter running in-process.

# You can display SQL statements and stats for debugging if needed.

# Enable JDBC batching.

Full Sample Application

A working sample application is available on GitHub.

What's next