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 JPA、PostgreSQL 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 上找到可運作的範例應用程式。
後續步驟
- 進一步瞭解 Spring Data JPA。
- 進一步瞭解 Hibernate ORM。
- 在 GitHub 上查看 PGAdapter 存放區。
- 在 GitHub 上提交問題,以回報錯誤或提出 PGAdapter 相關問題。
- 將 Spanner 與 Spring Data JPA (GoogleSQL 方言) 整合。