将 Spanner 与 Spring Data JPA(PostgreSQL 方言)集成

Spring Data JPA 是更大的 Spring Data 系列的一部分,它可让您更轻松地实现基于 JPA 的代码库。Spring Data JPA 支持 PostgreSQL 和各种其他数据库系统。它会在应用与数据库之间添加一个抽象层,使应用能够更轻松地从一个数据库系统移植到另一个数据库系统。

为 Spanner PostgreSQL 方言数据库设置 Spring Data JPA

您可以使用标准 PostgreSQL Hibernate 方言和 PGAdapter 将 Spanner PostgreSQL 方言数据库与 Spring Data JPA 集成。

如需查看示例,请参阅 GitHub 上的完整有效的示例应用

依赖项

在项目中,为 Spring Data JPAPostgreSQL JDBC 驱动程序PGAdapter 添加 Apache Maven 依赖项。

  <dependencies>
    <!-- Spring Data JPA -->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <!-- Add the PostgreSQL JDBC driver -->
    <dependency>
      <groupId>org.postgresql</groupId>
      <artifactId>postgresql</artifactId>
    </dependency>
    <!-- Add PGAdapter as a dependency, so we can start it in-process -->
    <dependency>
      <groupId>com.google.cloud</groupId>
      <artifactId>google-cloud-spanner-pgadapter</artifactId>
    </dependency>
  </dependencies>

在进程中启动 PGAdapter

将以下方法添加到您的应用中,以便直接从 Java 应用启动 PGAdapter。PGAdapter 与应用在同一 JVM 中运行,并且应用会连接到 localhost:port 上的 PGAdapter。

  /** 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);
    server.startServer();
    server.awaitRunning();

    return server;
  }

配置

配置 application.properties 以使用 PostgreSQL Hibernate 拨号器和 PostgreSQL JDBC 驱动程序。配置 PostgreSQL JDBC 驱动程序,以通过 PGAdapter 连接到 PostgreSQL 方言数据库。

# The example uses the standard PostgreSQL Hibernate dialect.
spring.jpa.database-platform=org.hibernate.dialect.PostgreSQLDialect

# Defining these properties here makes it a bit easier to build the connection string.
# Change these to match your Cloud Spanner PostgreSQL-dialect database.
spanner.project=my-project
spanner.instance=my-instance
spanner.database=my-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.
spanner.ddl_transaction_mode=options=-c%20spanner.ddl_transaction_mode=AutocommitExplicitTransaction

# This is the connection string to PGAdapter running in-process.
spring.datasource.url=jdbc:postgresql://localhost:9432/projects%2F${spanner.project}%2Finstances%2F${spanner.instance}%2Fdatabases%2F${spanner.database}?${spanner.ddl_transaction_mode}

# You can display SQL statements and stats for debugging if needed.
spring.jpa.properties.hibernate.show_sql=true
spring.jpa.properties.hibernate.format_sql=true

# Enable JDBC batching.
spring.jpa.properties.hibernate.jdbc.batch_size=100
spring.jpa.properties.hibernate.order_inserts=true

完整示例应用

GitHub 提供了一个有效的示例应用

后续步骤