Getting Started with Cloud Spanner in Java

Getting Started with Cloud Spanner in Java

Objectives

This tutorial walks you through the following steps using the Cloud Spanner client library for Java:

  • Create a Cloud Spanner instance and database.
  • Write, read, and execute SQL queries on data in the database.
  • Update the database schema.
  • Update data using a read-write transaction.
  • Add a secondary index to the database.
  • Use the index to read and execute SQL queries on data.
  • Retrieve data using a read-only transaction.

Costs

This tutorial uses Cloud Spanner, which is a billable component of the Google Cloud Platform. For information on the cost of using Cloud Spanner, see Pricing.

Before you begin

  1. Complete the steps described in Set Up, which covers creating and setting a default Google Cloud Platform project, enabling billing, enabling the Cloud Spanner API, and setting up OAuth 2.0 to get authentication credentials to use the Cloud Spanner API.
    In particular, ensure that you run gcloud auth application-default login to set up your local development environment with authentication credentials.

  2. Install the following on your development machine if they are not already installed:

  3. Clone the sample app repository to your local machine:

    git clone https://github.com/GoogleCloudPlatform/java-docs-samples.git
    

    Alternatively, you can download the sample as a zip file and extract it.

  4. Change to the directory that contains the Cloud Spanner sample code:

    cd java-docs-samples/spanner/cloud-client
    

Create an instance

When you first use Cloud Spanner, you must create an instance, which is an allocation of resources that are used by Cloud Spanner databases. When you create an instance, you choose an instance configuration, which determines where your data is stored, and also the number of nodes to use, which determines the amount of serving and storage resources in your instance.

Execute the following command to create a Cloud Spanner instance in the region us-central1 with 1 node:

gcloud spanner instances create test-instance --config=regional-us-central1 \
  --description="Test Instance" --nodes=1

Note that this creates an instance with the following characteristics:

  • Instance ID test-instance
  • Display name Test Instance
  • Instance configuration regional-us-central1 (Regional configurations store data in one region, while multi-region configurations distribute data across multiple regions. Learn more in Instances.)
  • Node count of 1 (node_count corresponds to the amount of serving and storage resources available to databases in the instance. Learn more in Node count.)

You should see:

Creating instance...done.

Look through sample files

The samples repo contains a sample that shows how to use Cloud Spanner with Java.

The pom.xml adds the Cloud Spanner client library for Java to the project's dependencies and configures the assembly plugin to build an executable JAR file with the Java class defined in this tutorial.

Build the sample from the spanner/cloud-client directory:

mvn package
Take a look through the SpannerSample.java file, which shows how to use Cloud Spanner. The code shows how to create and use a new database. The data uses the example schema shown in the Schema and Data Model page.

Create a database

Create a database called example-db in the instance called test-instance by running the following at the command line.

java -jar target/spanner-google-cloud-samples-1.0.8-jar-with-dependencies.jar \
createdatabase test-instance example-db

You should see:

Created database [example-db]

You have just created a Cloud Spanner database. The following is the code that created the database.

static void createDatabase(DatabaseAdminClient dbAdminClient, DatabaseId id) {
  Operation<Database, CreateDatabaseMetadata> op = dbAdminClient
      .createDatabase(
          id.getInstanceId().getInstance(),
          id.getDatabase(),
          Arrays.asList(
              "CREATE TABLE Singers (\n"
                  + "  SingerId   INT64 NOT NULL,\n"
                  + "  FirstName  STRING(1024),\n"
                  + "  LastName   STRING(1024),\n"
                  + "  SingerInfo BYTES(MAX)\n"
                  + ") PRIMARY KEY (SingerId)",
              "CREATE TABLE Albums (\n"
                  + "  SingerId     INT64 NOT NULL,\n"
                  + "  AlbumId      INT64 NOT NULL,\n"
                  + "  AlbumTitle   STRING(MAX)\n"
                  + ") PRIMARY KEY (SingerId, AlbumId),\n"
                  + "  INTERLEAVE IN PARENT Singers ON DELETE CASCADE"));
  Database db = op.waitFor().getResult();
  System.out.println("Created database [" + db.getId() + "]");
}

The code also defines two tables, Singers and Albums, for a basic music application. These tables are used throughout this page. Take a look at the example schema if you haven't already.

The next step is to write data to your database.

Create a database client

Before you can do reads or writes, you must create a DatabaseClient. You can think of a DatabaseClient as a database connection: all of your interactions with Cloud Spanner must go through a DatabaseClient. Typically you create a DatabaseClient when your application starts up, then you re-use that DatabaseClient to read, write, and execute transactions.

SpannerOptions options = SpannerOptions.newBuilder().build();
Spanner spanner = options.getService();
try {
  String command = args[0];
  DatabaseId db = DatabaseId.of(options.getProjectId(), args[1], args[2]);
  DatabaseClient dbClient = spanner.getDatabaseClient(db);
  DatabaseAdminClient dbAdminClient = spanner.getDatabaseAdminClient();

Each client uses resources in Cloud Spanner, so it is good practice to close unneeded clients by calling close().

Read more in the DatabaseClient Javadoc reference.

Write data

You write data using a Mutation object. A Mutation object is a container for mutation operations. A Mutation represents a sequence of inserts, updates, deletes, and so on that can be applied atomically to different rows and tables in a Cloud Spanner database.

The newInsertBuilder() method in the Mutation class constructs an INSERT mutation, which inserts a new row in a table. If the row already exists, the write fails. Alternatively, you can use the newInsertOrUpdateBuilder() method to construct an INSERT_OR_UPDATE mutation, which updates column values if the row already exists.

The write() method in the DatabaseClient class writes the mutations. All mutations in a single batch are applied atomically.

This code shows how to write the data:

static final List<Singer> SINGERS =
    Arrays.asList(
        new Singer(1, "Marc", "Richards"),
        new Singer(2, "Catalina", "Smith"),
        new Singer(3, "Alice", "Trentor"),
        new Singer(4, "Lea", "Martin"),
        new Singer(5, "David", "Lomond"));

static final List<Album> ALBUMS =
    Arrays.asList(
        new Album(1, 1, "Total Junk"),
        new Album(1, 2, "Go, Go, Go"),
        new Album(2, 1, "Green"),
        new Album(2, 2, "Forever Hold Your Peace"),
        new Album(2, 3, "Terrified"));
static void writeExampleData(DatabaseClient dbClient) {
  List<Mutation> mutations = new ArrayList<>();
  for (Singer singer : SINGERS) {
    mutations.add(
        Mutation.newInsertBuilder("Singers")
            .set("SingerId")
            .to(singer.singerId)
            .set("FirstName")
            .to(singer.firstName)
            .set("LastName")
            .to(singer.lastName)
            .build());
  }
  for (Album album : ALBUMS) {
    mutations.add(
        Mutation.newInsertBuilder("Albums")
            .set("SingerId")
            .to(album.singerId)
            .set("AlbumId")
            .to(album.albumId)
            .set("AlbumTitle")
            .to(album.albumTitle)
            .build());
  }
  dbClient.write(mutations);
}

(For details about the data, see the example schema for the Singers and Albums tables.)

Run the sample using the write argument.

java -jar target/spanner-google-cloud-samples-1.0.8-jar-with-dependencies.jar \
write test-instance example-db

Query data using SQL

Cloud Spanner supports a native SQL interface for reading data, which you can access on the command line using the gcloud command-line tool or programmatically using the Cloud Spanner client library for Java.

On the command line

Execute the following SQL statement to read the values of all columns from the Albums table:

gcloud spanner databases execute-sql example-db --instance=test-instance --sql='SELECT SingerId, AlbumId, AlbumTitle FROM Albums'

The result should be:

SingerId AlbumId AlbumTitle
1        1       Total Junk
1        2       Go, Go, Go
2        1       Green
2        2       Forever Hold Your Peace
2        3       Terrified

Using the Cloud Spanner client library for Java

In addition to executing a SQL statement on the command line, you can issue the same SQL statement programmatically using the Cloud Spanner client library for Java.

The following methods and classes are used to run the SQL query:

  • The singleUse() method in the DatabaseClient class: use this to read the value of one or more columns from one or more rows in a Cloud Spanner table. singleUse() returns a ReadContext object, which is used for running a read or SQL statement.
  • The executeQuery() method of the ReadContext class: use this method to execute a query against a database.
  • The Statement class: use this to construct a SQL string.
  • The ResultSet class: use this to access the data returned by a SQL statement or read call.

Here's how to issue the query and access the data:

static void query(DatabaseClient dbClient) {
  // singleUse() can be used to execute a single read or query against Cloud Spanner.
  ResultSet resultSet =
      dbClient
          .singleUse()
          .executeQuery(Statement.of("SELECT SingerId, AlbumId, AlbumTitle FROM Albums"));
  while (resultSet.next()) {
    System.out.printf(
        "%d %d %s\n", resultSet.getLong(0), resultSet.getLong(1), resultSet.getString(2));
  }
}

Run the sample using the query argument.

java -jar target/spanner-google-cloud-samples-1.0.8-jar-with-dependencies.jar \
query test-instance example-db

You should see the following result:

1 1 Total Junk
1 2 Go, Go, Go
2 1 Green
2 2 Forever Hold Your Peace
2 3 Terrified

Read data using the read API

In addition to Cloud Spanner's SQL interface, Cloud Spanner also supports a read interface.

Use the read() method of the ReadContext class to read rows from the database. Use a KeySet object to define a collection of keys and key ranges to read.

Here's how to read the data:

static void read(DatabaseClient dbClient) {
  ResultSet resultSet =
      dbClient
          .singleUse()
          .read("Albums",
              // KeySet.all() can be used to read all rows in a table. KeySet exposes other
              // methods to read only a subset of the table.
              KeySet.all(),
              Arrays.asList("SingerId", "AlbumId", "AlbumTitle"));
  while (resultSet.next()) {
    System.out.printf(
        "%d %d %s\n", resultSet.getLong(0), resultSet.getLong(1), resultSet.getString(2));
  }
}

Run the sample using the read argument.

java -jar target/spanner-google-cloud-samples-1.0.8-jar-with-dependencies.jar \
read test-instance example-db

You should see output similar to:

1 1 Total Junk
1 2 Go, Go, Go
2 1 Green
2 2 Forever Hold Your Peace
2 3 Terrified

Update the database schema

Assume you need to add a new column called MarketingBudget to the Albums table. Adding a new column to an existing table requires an update to your database schema. Cloud Spanner supports schema updates to a database while the database continues to serve traffic. Schema updates do not require taking the database offline and they do not lock entire tables or columns; you can continue writing data to the database during the schema update. Read more about supported schema updates and schema change performance in Updating schemas.

Add a column

You can add a column on the command line using the gcloud command-line tool or programmatically using the Cloud Spanner client library for Java.

On the command line

Use the following ALTER TABLE command to add the new column to the table:

gcloud spanner databases ddl update example-db --instance=test-instance \
  --ddl='ALTER TABLE Albums ADD COLUMN MarketingBudget INT64'

You should see:

DDL updating...done.

Using the Cloud Spanner client library for Java

Use the updateDatabaseDdl() method of the DatabaseAdminClient class to modify the schema:

static void addMarketingBudget(DatabaseAdminClient adminClient, DatabaseId dbId) {
  adminClient.updateDatabaseDdl(dbId.getInstanceId().getInstance(),
      dbId.getDatabase(),
      Arrays.asList("ALTER TABLE Albums ADD COLUMN MarketingBudget INT64"),
      null).waitFor();
  System.out.println("Added MarketingBudget column");
}

Run the sample using the addmarketingbudget argument.

java -jar target/spanner-google-cloud-samples-1.0.8-jar-with-dependencies.jar \
addmarketingbudget test-instance example-db

You should see:

Added MarketingBudget column.

Write data to the new column

The following code writes data to the new column. It sets MarketingBudget to 100000 for the row keyed by Albums(1, 1) and to 500000 for the row keyed by Albums(2, 2).

static void update(DatabaseClient dbClient) {
  // Mutation can be used to update/insert/delete a single row in a table. Here we use
  // newUpdateBuilder to create update mutations.
  List<Mutation> mutations =
      Arrays.asList(
          Mutation.newUpdateBuilder("Albums")
              .set("SingerId")
              .to(1)
              .set("AlbumId")
              .to(1)
              .set("MarketingBudget")
              .to(100000)
              .build(),
          Mutation.newUpdateBuilder("Albums")
              .set("SingerId")
              .to(2)
              .set("AlbumId")
              .to(2)
              .set("MarketingBudget")
              .to(500000)
              .build());
  // This writes all the mutations to Cloud Spanner atomically.
  dbClient.write(mutations);
}

Run the sample using the update argument.

java -jar target/spanner-google-cloud-samples-1.0.8-jar-with-dependencies.jar \
update test-instance example-db

You can also execute a SQL query or a read call to fetch the values that you just wrote.

Here's the code to execute the query:

static void queryMarketingBudget(DatabaseClient dbClient) {
  // Rows without an explicit value for MarketingBudget will have a MarketingBudget equal to
  // null.
  ResultSet resultSet =
      dbClient
          .singleUse()
          .executeQuery(Statement.of("SELECT SingerId, AlbumId, MarketingBudget FROM Albums"));
  while (resultSet.next()) {
    System.out.printf(
        "%d %d %s\n",
        resultSet.getLong("SingerId"),
        resultSet.getLong("AlbumId"),
        // We check that the value is non null. ResultSet getters can only be used to retrieve
        // non null values.
        resultSet.isNull("MarketingBudget") ? "NULL" : resultSet.getLong("MarketingBudget"));
  }
}

To execute this query, run the sample using the querymarketingbudget argument.

java -jar target/spanner-google-cloud-samples-1.0.8-jar-with-dependencies.jar \
querymarketingbudget test-instance example-db

You should see:

1 1 100000
1 2 NULL
2 1 NULL
2 2 500000
2 3 NULL

Update data using a read-write transaction

Suppose that sales of Albums(1, 1) are lower than expected. As a result, you want to move $200,000 from the marketing budget of Albums(2, 2) to Albums(1, 1), but only if the budget of Albums(2, 2) is at least $300,000.

Because this transaction might write data that differs depending on the values that are read, you should use a read-write transaction to perform the reads and writes atomically.

Use the TransactionRunner interface for executing a body of work in the context of a read-write transaction. This interface contains the method run(), which is used to execute a read-write transaction, with retries as necessary. The readWriteTransaction() method of the DatabaseClient class returns a TransactionRunner object for executing a single logical transaction.

The TransactionRunner.TransactionCallable class contains a run() method for performing a single attempt of a transaction. run() takes a TransactionContext object, which is a context for a transaction.

The sample uses the Struct class, which is handy for storing the results of the readRow() calls. The sample also uses the Key class, which represents a row key in a Cloud Spanner table or index.

Here's the code to run the transaction:

static void writeWithTransaction(DatabaseClient dbClient) {
  dbClient
      .readWriteTransaction()
      .run(
          new TransactionCallable<Void>() {
            @Override
            public Void run(TransactionContext transaction) throws Exception {
              // Transfer marketing budget from one album to another. We do it in a transaction to
              // ensure that the transfer is atomic.
              Struct row =
                  transaction.readRow("Albums", Key.of(2, 2), Arrays.asList("MarketingBudget"));
              long album2Budget = row.getLong(0);
              // Transaction will only be committed if this condition still holds at the time of
              // commit. Otherwise it will be aborted and the callable will be rerun by the
              // client library.
              if (album2Budget >= 300000) {
                long album1Budget =
                    transaction
                        .readRow("Albums", Key.of(1, 1), Arrays.asList("MarketingBudget"))
                        .getLong(0);
                long transfer = 200000;
                album1Budget += transfer;
                album2Budget -= transfer;
                transaction.buffer(
                    Mutation.newUpdateBuilder("Albums")
                        .set("SingerId")
                        .to(1)
                        .set("AlbumId")
                        .to(1)
                        .set("MarketingBudget")
                        .to(album1Budget)
                        .build());
                transaction.buffer(
                    Mutation.newUpdateBuilder("Albums")
                        .set("SingerId")
                        .to(2)
                        .set("AlbumId")
                        .to(2)
                        .set("MarketingBudget")
                        .to(album2Budget)
                        .build());
              }
              return null;
            }
          });
}

Run the sample using the writetransaction argument.

java -jar target/spanner-google-cloud-samples-1.0.8-jar-with-dependencies.jar \
writetransaction test-instance example-db

Query the data again:

java -jar target/spanner-google-cloud-samples-1.0.8-jar-with-dependencies.jar \
querymarketingbudget test-instance example-db

You should see that $200,000 was successfully transferred from Albums(2, 2) to Albums(1, 1):

1 1 300000
1 2 NULL
2 1 NULL
2 2 300000
2 3 NULL

Use a secondary index

Suppose you wanted to fetch all rows of Albums that have AlbumTitle values in a certain range. You could read all values from the AlbumTitle column using a SQL statement or a read call, and then discard the rows that don't meet the criteria, but doing this full table scan is expensive, especially for tables with a lot of rows. Instead you can speed up the retrieval of rows when searching by non-primary key columns by creating a secondary index on the table.

Adding a secondary index to an existing table requires a schema update. Like other schema updates, Cloud Spanner supports adding an index while the database continues to serve traffic. Cloud Spanner populates the index with data (aka "backfills") under the hood. Backfills might take a few minutes to complete, but you don't have to take the database offline or avoid writing to certain tables or columns during this process. For more details, see index backfilling.

Add a secondary index

You can add an index on the command line using the gcloud command line tool or programmatically using the Cloud Spanner client library for Java.

On the command line

Use the following CREATE INDEX command to add an index to the database:

gcloud spanner databases ddl update example-db --instance=test-instance \
  --ddl='CREATE INDEX AlbumsByAlbumTitle ON Albums(AlbumTitle)'

You should see:

DDL updating...done.

Using the Cloud Spanner client library for Java

Use the updateDatabaseDdl() method of the DatabaseAdminClient class to add an index:

static void addIndex(DatabaseAdminClient adminClient, DatabaseId dbId) {
  adminClient.updateDatabaseDdl(dbId.getInstanceId().getInstance(),
      dbId.getDatabase(),
      Arrays.asList("CREATE INDEX AlbumsByAlbumTitle ON Albums(AlbumTitle)"),
      null).waitFor();
  System.out.println("Added AlbumsByAlbumTitle index");
}

Run the sample using the addindex argument.

java -jar target/spanner-google-cloud-samples-1.0.8-jar-with-dependencies.jar \
addindex test-instance example-db

Adding an index can take a few minutes. After the index is added, you should see:

Added the AlbumsByAlbumTitle index.

Query using the index

You can query using the new index either on the command line or using the client library.

On the command line

Execute a SQL statement using the gcloud command-line tool to fetch AlbumId, AlbumTitle, and MarketingBudget from Albums using the AlbumsByAlbumTitle index, for the range of AlbumsTitle in ["Aardvark", "Goo").

gcloud spanner databases execute-sql example-db --instance=test-instance --sql='SELECT AlbumId, AlbumTitle, MarketingBudget FROM Albums@{FORCE_INDEX=AlbumsByAlbumTitle} WHERE AlbumTitle >= "Aardvark" AND AlbumTitle < "Goo"'

The result should be:

AlbumId  AlbumTitle               MarketingBudget
2        Go, Go, Go
2        Forever Hold Your Peace  300000

Using the Cloud Spanner client library for Java

The code to programmatically use the index is similar to the query code used earlier.

static void queryUsingIndex(DatabaseClient dbClient) {
  Statement statement = Statement
      // We use FORCE_INDEX hint to specify which index to use. For more details see
      // https://cloud.google.com/spanner/docs/query-syntax#from-clause
      .newBuilder("SELECT AlbumId, AlbumTitle, MarketingBudget\n"
          + "FROM Albums@{FORCE_INDEX=AlbumsByAlbumTitle}\n"
          + "WHERE AlbumTitle >= @StartTitle AND AlbumTitle < @EndTitle")
      // We use @BoundParameters to help speed up frequently executed queries.
      //  For more details see https://cloud.google.com/spanner/docs/sql-best-practices
      .bind("StartTitle").to("Aardvark")
      .bind("EndTitle").to("Goo")
      .build();

  ResultSet resultSet = dbClient.singleUse().executeQuery(statement);
  while (resultSet.next()) {
    System.out.printf(
        "%d %s %s\n",
        resultSet.getLong("AlbumId"),
        resultSet.getString("AlbumTitle"),
        resultSet.isNull("MarketingBudget") ? "NULL" : resultSet.getLong("MarketingBudget"));
  }
}

Run the sample using the queryindex argument.

java -jar target/spanner-google-cloud-samples-1.0.8-jar-with-dependencies.jar \
queryindex test-instance example-db

You should see output similar to:

2 Go, Go, Go NULL
2 Forever Hold Your Peace 300000

For more details, consult the reference for:

Read using the index

To read using the index, use the readUsingIndex() method of the ReadContext class.

The following code fetches all AlbumId, and AlbumTitle columns from the AlbumsByAlbumTitle index.

static void readUsingIndex(DatabaseClient dbClient) {
  ResultSet resultSet =
      dbClient
          .singleUse()
          .readUsingIndex(
              "Albums",
              "AlbumsByAlbumTitle",
              KeySet.all(),
              Arrays.asList("AlbumId", "AlbumTitle"));
  while (resultSet.next()) {
    System.out.printf("%d %s\n", resultSet.getLong(0), resultSet.getString(1));
  }
}

Run the sample using the readindex argument.

java -jar target/spanner-google-cloud-samples-1.0.8-jar-with-dependencies.jar \
readindex test-instance example-db

You should see:

2 Forever Hold Your Peace
2 Go, Go, Go
1 Green
3 Terrified
1 Total Junk

Add an index with a STORING clause

You might have noticed that the read example above did not include reading the MarketingBudget column. This is because Cloud Spanner's read interface does not support the ability to join an index with a data table to look up values that are not stored in the index.

Create an alternate definition of AlbumsByAlbumTitle that stores a copy of MarketingBudget in the index.

On the command line

gcloud spanner databases ddl update example-db --instance=test-instance \
  --ddl='CREATE INDEX AlbumsByAlbumTitle2 ON Albums(AlbumTitle) STORING (MarketingBudget)'

Adding an index can take a few minutes. After the index is added, you should see:

DDL updating...done.

Using the Cloud Spanner client library for Java

Use the updateDatabaseDdl() method of the DatabaseAdminClient class to add an index with a STORING clause:

static void addStoringIndex(DatabaseAdminClient adminClient, DatabaseId dbId) {
  adminClient.updateDatabaseDdl(dbId.getInstanceId().getInstance(),
      dbId.getDatabase(),
      Arrays.asList(
          "CREATE INDEX AlbumsByAlbumTitle2 ON Albums(AlbumTitle) STORING (MarketingBudget)"),
      null).waitFor();
  System.out.println("Added AlbumsByAlbumTitle2 index");
}

Run the sample using the addstoringindex argument.

java -jar target/spanner-google-cloud-samples-1.0.8-jar-with-dependencies.jar \
addstoringindex test-instance example-db

Adding an index can take a few minutes. After the index is added, you should see:

Added the AlbumsByAlbumTitle2 index.

Now you can execute a read that fetches all AlbumId, AlbumTitle, and MarketingBudget columns from the AlbumsByAlbumTitle2 index:

static void readStoringIndex(DatabaseClient dbClient) {
  // We can read MarketingBudget also from the index since it stores a copy of MarketingBudget.
  ResultSet resultSet =
      dbClient
          .singleUse()
          .readUsingIndex(
              "Albums",
              "AlbumsByAlbumTitle2",
              KeySet.all(),
              Arrays.asList("AlbumId", "AlbumTitle", "MarketingBudget"));
  while (resultSet.next()) {
    System.out.printf(
        "%d %s %s\n",
        resultSet.getLong(0),
        resultSet.getString(1),
        resultSet.isNull("MarketingBudget") ? "NULL" : resultSet.getLong("MarketingBudget"));
  }
}

Run the sample using the readstoringindex argument.

java -jar target/spanner-google-cloud-samples-1.0.8-jar-with-dependencies.jar \
readstoringindex test-instance example-db

You should see output similar to:

2 Forever Hold Your Peace 300000
2 Go, Go, Go NULL
1 Green NULL
3 Terrified NULL
1 Total Junk 300000

Retrieve data using read-only transactions

Suppose you want to execute more than one read at the same timestamp. Read-only transactions observe a consistent prefix of the transaction commit history, so your application always gets consistent data. Use a ReadOnlyTransaction object for executing read-only transactions. Use the readOnlyTransaction() method of the DatabaseClient class to get a ReadOnlyTransaction object.

The following shows how to run a query and perform a read in the same read-only transaction:

static void readOnlyTransaction(DatabaseClient dbClient) {
  // ReadOnlyTransaction must be closed by calling close() on it to release resources held by it.
  // We use a try-with-resource block to automatically do so.
  try (ReadOnlyTransaction transaction = dbClient.readOnlyTransaction()) {
    ResultSet queryResultSet =
        transaction.executeQuery(
            Statement.of("SELECT SingerId, AlbumId, AlbumTitle FROM Albums"));
    while (queryResultSet.next()) {
      System.out.printf(
          "%d %d %s\n",
          queryResultSet.getLong(0), queryResultSet.getLong(1), queryResultSet.getString(2));
    }
    ResultSet readResultSet =
        transaction.read(
            "Albums", KeySet.all(), Arrays.asList("SingerId", "AlbumId", "AlbumTitle"));
    while (readResultSet.next()) {
      System.out.printf(
          "%d %d %s\n",
          readResultSet.getLong(0), readResultSet.getLong(1), readResultSet.getString(2));
    }
  }
}

Run the sample using the readonlytransaction argument.

java -jar target/spanner-google-cloud-samples-1.0.8-jar-with-dependencies.jar \
readonlytransaction test-instance example-db

You should see output similar to:

2 2 Forever Hold Your Peace
1 2 Go, Go, Go
2 1 Green
2 3 Terrified
1 1 Total Junk
1 1 Total Junk
1 2 Go, Go, Go
2 1 Green
2 2 Forever Hold Your Peace
2 3 Terrified

Cleanup

To avoid incurring additional charges to your Google Cloud Platform account for the resources used in this tutorial, drop the database and delete the instance that you created.

Delete the database

If you delete an instance, all databases within it are automatically deleted. This step shows how to delete a database without deleting an instance (you would still incur charges for the instance).

On the command line

gcloud spanner databases delete example-db --instance=test-instance

Using the GCP Console

  1. Go to the Cloud Spanner Instances page in the Google Cloud Platform Console.
    Go to the Cloud Spanner Instances page
  2. Click the instance.
  3. Click the database that you want to delete.
  4. In the Database details page, click Delete.
  5. Confirm that you want to delete the database and click Delete.

Delete the instance

Deleting an instance automatically drops all databases created in that instance.

On the command line

gcloud spanner instances delete test-instance

Using the GCP Console

  1. Go to the Cloud Spanner Instances page in the Google Cloud Platform Console.
    Go to the Cloud Spanner Instances page
  2. Click your instance.
  3. Click Delete.
  4. Confirm that you want to delete the instance and click Delete.

What's next

Was this page helpful? Let us know how we did:

Send feedback about...

Cloud Spanner Documentation