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

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

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

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

要查看示例,请参阅 可运行的示例应用 GitHub。

依赖项

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

  <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

将以下方法添加到您的应用中以启动 PGAdapter Java 应用。PGAdapter 与 并且应用会连接到 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);
    server.startServer();
    server.awaitRunning();

    return server;
  }

配置

application.properties 配置为使用 PostgreSQL Hibernate Dialect 和 PostgreSQL JDBC 驱动程序。配置 PostgreSQL 用于通过 PGAdapter 连接到 PostgreSQL 方言数据库的 JDBC 驱动程序。

# 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

完整示例应用

有效的示例应用是 。

后续步骤