Cloud Spanner
Cloud Spanner is a scalable, enterprise-grade, globally-distributed, and strongly consistent database service built for the cloud specifically to combine the benefits of relational database structure with non-relational horizontal scale. It delivers high-performance transactions and strong consistency across rows, regions, and continents with an industry-leading 99.999% availability SLA, no planned downtime, and enterprise-grade security. Cloud Spanner revolutionizes database administration and management and makes application development more efficient.

Cloud Spanner Instance

Enable API

1
gcloud services enable spanner.googleapis.com
Copied!

Create an Instance

1
gcloud spanner instances create spanner-instance \
2
--config=regional-us-central1 \
3
--nodes=1 --description="A Spanner Instance"
Copied!
This example creates a new regional instance (i.e., spanning across zones within the same region). Cloud Spanner supports multi-regional configuration to span across multiple regions for highest availability.

Create a Database

A Cloud Spanner instance can host multiple databases, that each contains its own tables.
1
gcloud spanner databases create orders \
2
--instance=spanner-instance
Copied!

Connect to Instance

There is no interactive CLI to Cloud Spanner. You can create table and execute SQL statements from the Cloud Console, or from gcloud command line. Following are some common operations:

List Databases

1
gcloud spanner databases list --instance=spanner-instance
Copied!

Execute SQL Statements

1
gcloud spanner databases execute-sql orders \
2
--instance=spanner-instance \
3
--sql="SELECT 1"
Copied!

Show Query Plan

1
gcloud spanner databases execute-sql orders \
2
--instance=spanner-instance \
3
--sql="SELECT 1" \
4
--query-mode=PLAN
Copied!

Create a Table

Create a DDL file, schema.ddl:
1
CREATE TABLE orders (
2
order_id STRING(36) NOT NULL,
3
description STRING(255),
4
creation_timestamp TIMESTAMP,
5
) PRIMARY KEY (order_id);
6
7
CREATE TABLE order_items (
8
order_id STRING(36) NOT NULL,
9
order_item_id STRING(36) NOT NULL,
10
description STRING(255),
11
quantity INT64,
12
) PRIMARY KEY (order_id, order_item_id),
13
INTERLEAVE IN PARENT orders ON DELETE CASCADE;
Copied!
Cloud Spanner differs from traditional RDBMS in a several ways:
  • No server-side automatic ID generation.
  • Avoid monodically increasing IDs - I.e., no auto incremented ID, because it may create hot spots in partitions.
  • No foreign key constraints.
Cloud Spanner, being horizontally scalable and shards data with your keys, prefers the following:
  • UUIDv4 as IDs - It's random and can be partitioned easily.
  • Parent-Children relationship encoded using a compose primary key.
  • Colocate Parent-Children data using Interleave tables - If accessing parent means children data is also likely to be read, interleaving allows children data to be colocated with parent row in the same parition.
Use gcloud to execute the DDL:
1
gcloud spanner databases ddl update orders \
2
--instance=spanner-instance \
3
--ddl="$(<schema.ddl)"
Copied!

Spring Data Spanner Starter

The easiest way to access Cloud Spanner is using Spring Cloud GCP's Spring Data Spanner starter. This starter provides full Spring Data support for Cloud Spanner while implementing idiomatic access patterns.
Spring Data Feature
Supported
ORM
Declarative Transaction
Repository
REST Repository
Query methods
Query annotation
Pagination
Events
Auditing

Dependency

Add the Spring Data Spanner starter:
Maven
Gradle
1
<dependency>
2
<groupId>org.springframework.cloud</groupId>
3
<artifactId>spring-cloud-gcp-starter-data-spanner</artifactId>
4
</dependency>
Copied!
1
compile group: 'org.springframework.cloud', name: 'spring-cloud-gcp-starter-data-spanner'
Copied!

Configuration

Configure Cloud Spanner instance and database to connect to.
application.properties
1
spring.cloud.gcp.spanner.instance-id=spanner-instance
2
spring.cloud.gcp.spanner.database=orders
Copied!
Notice that there is no explicit configuration for username/password. Cloud Spanner authentication uses the GCP credential (either your user credential, or Service Account credential), and authorization is configured via Identity Access Management (IAM).

ORM

Spring Data Cloud Spanner allows you to map domain POJOs to Cloud Spanner tables via annotations. Read the Spring Data Spanner reference documentation for details
Order.java
1
import java.time.LocalDateTime;
2
import java.util.List;
3
import lombok.Data;
4
import org.springframework.cloud.gcp.data.spanner.core.mapping.*;
5
6
@Table(name="orders")
7
@Data // Lombok to generate getter/setters
8
class Order {
9
@PrimaryKey
10
@Column(name="order_id")
11
private String id;
12
13
private String description;
14
15
@Column(name="creation_timestamp")
16
private LocalDateTime timestamp;
17
18
@Interleaved
19
private List<OrderItem> items;
20
}
Copied!
OrderItem.java
1
import lombok.Data;
2
import org.springframework.cloud.gcp.data.spanner.core.mapping.*;
3
4
@Table(name="order_items")
5
@Data // Lombok to generate getter/setters
6
class OrderItem {
7
@PrimaryKey(keyOrder = 1)
8
@Column(name="order_id")
9
private String orderId;
10
11
@PrimaryKey(keyOrder = 2)
12
@Column(name="order_item_id")
13
private String orderItemId;
14
15
private String description;
16
private Long quantity;
17
}
Copied!

Repository

Use Spring Data repository to quickly get CRUD access to the Cloud Spanner tables.
OrderRepository.java
1
package com.example.demo;
2
3
import org.springframework.cloud.gcp.data.spanner.repository.SpannerRepository;
4
import org.springframework.stereotype.Repository;
5
6
@Repository
7
public interface OrderRepository extends SpannerRepository<Order, String> {
8
}
Copied!
OrderItemRepoistory.java
1
package com.example.demo;
2
3
import lombok.Data;
4
import org.springframework.cloud.gcp.data.spanner.core.mapping.*;
5
6
@Table(name="order_items")
7
@Data
8
class OrderItem {
9
@PrimaryKey(keyOrder = 1)
10
@Column(name="order_id")
11
private String orderId;
12
13
@PrimaryKey(keyOrder = 2)
14
@Column(name="order_item_id")
15
private String orderItemId;
16
17
private String description;
18
private Long quantity;
19
}
Copied!
Order is the parent and has only a primary key. Spring Data repository's ID parameter type can be the type for the single key. OrderItem, however, has a composite key. Spring Data repository's ID parameter type must be Cloud Spanner's Key type for a composite key.
In a business logic service, you can utilize the repositories:
1
@Service
2
class OrderService {
3
private final OrderRepository orderRepository;
4
5
OrderService(OrderRepository orderRepository,
6
OrderItemRepository orderItemRepository) {
7
this.orderRepository = orderRepository;
8
}
9
10
@Transactional
11
Order createOrder(Order order) {
12
// Use UUID String representation for the ID
13
order.setId(UUID.randomUUID().toString());
14
15
// Set the creation time
16
order.setCreationTimestamp(LocalDateTime.now());
17
18
// Set the parent Order ID and children ID for each item.
19
if (order.getItems() != null) {
20
order.getItems().stream().forEach(orderItem -> {
21
orderItem.setOrderId(order.getId());
22
orderItem.setOrderItemId(UUID.randomUUID().toString());
23
});
24
}
25
26
// Children are saved in cascade.
27
return orderRepository.save(order);
28
}
29
}
Copied!

Rest Repository

Spring Data Rest can expose a Spring Data repository directly on a RESTful endpoint, and rendering the payload as JSON with HATEOS format. It supports common access patterns like pagination.
Add Spring Data Rest starter:
Maven
Gradle
1
<dependency>
2
<groupId>org.springframework.boot</groupId>
3
<artifactId>spring-boot-starter-data-rest</artifactId>
4
</dependency>
Copied!
1
compile group: 'org.springframework.boot', name: 'spring-boot-starter-data-rest'
Copied!
1
@RepositoryRestResource
2
interface OrderRepository extends SpannerRepository<Order, String> {
3
}
4
5
@RepositoryRestResource
6
interface OrderItemRepository extends SpannerRepository<OrderItem, Key> {
7
List<OrderItem> findAllByOrderId(String orderId);
8
}
Copied!
To access the endpoint for Order:
1
curl http://localhost:8080/orders
Copied!

Samples

JDBC

Cloud Spanner JDBC Driver can be used if you need raw JDBC access.

Dependency

Add Cloud Spanner JDBC Driver:
Maven
Gradle
1
<dependency>
2
<groupId>com.google.cloud</groupId>
3
<artifactId>google-cloud-spanner-jdbc</artifactId>
4
</dependency>
Copied!
1
compile group: 'com.google.cloud', name: 'google-cloud-spanner-jdbc'
Copied!
Use Spring Boot JDBC Starter to use JDBC Template:
Maven
Gradle
1
<dependency>
2
<groupId>org.springframework.boot</groupId>
3
<artifactId>spring-boot-starter-jdbc</artifactId>
4
</dependency>
Copied!
1
compile group: 'org.springframework.boot', name: 'spring-boot-starter-jdbc'
Copied!

Configuration

Cloud Spanner JDBC Driver Class:
1
com.google.cloud.spanner.jdbc.JdbcDriver
Copied!
Cloud Spanner JDBC URL format:
1
jdbc:cloudspanner:/projects/PROJECT_ID/instances/INSTANCE_ID/databases/DATABASE_NAME
Copied!
With Spring Data JDBC, you can configure the datasource:
application.properties
1
spring.datasource.driver-class-name=com.google.cloud.spanner.jdbc.JdbcDriver
2
spring.datasource.url=jdbc:cloudspanner:/projects/PROJECT_ID/instances/spanner-instance/databases/orders
Copied!

Hibernate

Cloud Spanner Hibernate Dialect lets you use Cloud Spanner with Hibernate ORM. You can use Cloud Spanner with Hibernate from any Java application. When using Spring Boot, you can use the Hibernate Dialect with Spring Data JPA.

Dependency

Add both the Cloud Spanner JDBC driver and Cloud Spanner Hibernate Dialect:
Maven
Gradle
1
<dependency>
2
<groupId>com.google.cloud</groupId>
3
<artifactId>google-cloud-spanner-jdbc</artifactId>
4
</dependency>
5
<dependency>
6
<groupId>com.google.cloud</groupId>
7
<artifactId>google-cloud-spanner-hibernate-dialect</artifactId>
8
</dependency>
Copied!
1
compile group: 'com.google.cloud', name: 'google-cloud-spanner-jdbc'
2
compile group: 'com.google.cloud', name: 'google-cloud-spanner-hibernate-dialect'
Copied!
Add Spring Data JPA starter:
Maven
Gradle
1
<dependency>
2
<groupId>org.springframework.boot</groupId>
3
<artifactId>spring-boot-starter-data-jpa</artifactId>
4
</dependency>
Copied!
1
compile group: 'org.springframework.boot', name: 'spring-boot-starter-data-jpa'
Copied!

Configuration

Cloud Spanner Hibernate Dialect class:
1
com.google.cloud.spanner.hibernate.SpannerDialect
Copied!
Configure Spring Data JPA:
application.properties
1
spring.datasource.driver-class-name=com.google.cloud.spanner.jdbc.JdbcDriver
2
spring.datasource.url=jdbc:cloudspanner:/projects/PROJECT_ID/instances/spanner-instance/databases/orders
3
4
spring.jpa.database-platform=com.google.cloud.spanner.hibernate.SpannerDialect
Copied!

ORM

Use JPA annotations to map POJO to Cloud Spanner database tables.
In Cloud Spanner, parent-children relationship is modeled as a composite key. With JPA, use IdClass or EmbeddableId to map a composite key.
1
@Entity
2
@Table(name="orders")
3
class Order {
4
@Id
5
@Column(name="order_id")
6
private String id;
7
8
private String description;
9
10
@Column(name="creation_timestamp")
11
private LocalDateTime creationTimestamp;
12
13
@OneToMany(mappedBy = "order", cascade = CascadeType.ALL)
14
private List<OrderItem> items;
15
16
// Getter and Setter ...
17
}
18
19
@Embeddable
20
class OrderItemId implements Serializable {
21
@Column(name="order_id")
22
private String orderId;
23
24
@Column(name="order_item_id")
25
private String orderItemId;
26
27
// Getter and Setter ...
28
// Hashcode and Equals ...
29
}
30
31
@Entity
32
@Table(name="order_items")
33
class OrderItem {
34
@EmbeddedId
35
private OrderItemId orderItemId;
36
37
private String description;
38
private Long quantity;
39
40
@ManyToOne
41
@JoinColumn(name="order_id", insertable = false, updatable = false)
42
private Order order;
43
44
// Getter and Setter ...
45
}
Copied!

Repository

Use Spring Data repository for CRUD access to the tables.
1
@Repository
2
interface OrderRepository extends JpaRepository<Order, String> {
3
}
4
5
@Repository
6
interface OrderItemRepository extends JpaRepository<OrderItem, OrderItemId> {
7
}
Copied!

Rest Repository

Use Spring Data Rest to expose the repositories as RESTful services with HATEOS format.
1
@RepositoryRestResource
2
interface OrderRepository extends JpaRepository<Order, String> {
3
}
4
5
@RepositoryRestResource
6
interface OrderItemRepository extends JpaRepository<OrderItem, OrderItemId> {
7
}
Copied!

Sample

R2DBC

Cloud Spanner R2DBC driver let's you access Cloud Spanner data with reactive API.
Cloud Spanner R2DBC driver is under active development.
It can be used with Spring Data R2DBC using the Cloud Spanner R2DBC Dialect.

Samples

Last modified 1yr ago