Class SpannerClient
- All Implemented Interfaces:
com.google.api.gax.core.BackgroundResource
,AutoCloseable
The Cloud Spanner API can be used to manage sessions and execute transactions on data stored in Cloud Spanner databases.
This class provides the ability to make remote calls to the backing service through method calls that map to API methods. Sample code to get started:
// This snippet has been automatically generated and should be regarded as a code template only.
// It will require modifications to work:
// - It may require correct/in-range values for request initialization.
// - It may require specifying regional endpoints when creating the service client as shown in
// https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
try (SpannerClient spannerClient = SpannerClient.create()) {
DatabaseName database = DatabaseName.of("[PROJECT]", "[INSTANCE]", "[DATABASE]");
Session response = spannerClient.createSession(database);
}
Note: close() needs to be called on the SpannerClient object to clean up resources such as threads. In the example above, try-with-resources is used, which automatically calls close().
The surface of this class includes several types of Java methods for each of the API's methods:
- A "flattened" method. With this type of method, the fields of the request type have been converted into function parameters. It may be the case that not all fields are available as parameters, and not every API method will have a flattened method entry point.
- A "request object" method. This type of method only takes one parameter, a request object, which must be constructed before the call. Not every API method will have a request object method.
- A "callable" method. This type of method takes no parameters and returns an immutable API callable object, which can be used to initiate calls to the service.
See the individual methods for example code.
Many parameters require resource names to be formatted in a particular way. To assist with these names, this class includes a format method for each type of name, and additionally a parse method to extract the individual identifiers contained within names that are returned.
This class can be customized by passing in a custom instance of SpannerSettings to create(). For example:
To customize credentials:
// This snippet has been automatically generated and should be regarded as a code template only.
// It will require modifications to work:
// - It may require correct/in-range values for request initialization.
// - It may require specifying regional endpoints when creating the service client as shown in
// https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
SpannerSettings spannerSettings =
SpannerSettings.newBuilder()
.setCredentialsProvider(FixedCredentialsProvider.create(myCredentials))
.build();
SpannerClient spannerClient = SpannerClient.create(spannerSettings);
To customize the endpoint:
// This snippet has been automatically generated and should be regarded as a code template only.
// It will require modifications to work:
// - It may require correct/in-range values for request initialization.
// - It may require specifying regional endpoints when creating the service client as shown in
// https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
SpannerSettings spannerSettings = SpannerSettings.newBuilder().setEndpoint(myEndpoint).build();
SpannerClient spannerClient = SpannerClient.create(spannerSettings);
To use REST (HTTP1.1/JSON) transport (instead of gRPC) for sending and receiving requests over the wire:
// This snippet has been automatically generated and should be regarded as a code template only.
// It will require modifications to work:
// - It may require correct/in-range values for request initialization.
// - It may require specifying regional endpoints when creating the service client as shown in
// https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
SpannerSettings spannerSettings = SpannerSettings.newHttpJsonBuilder().build();
SpannerClient spannerClient = SpannerClient.create(spannerSettings);
Please refer to the GitHub repository's samples for more quickstart code snippets.
-
Nested Class Summary
Modifier and TypeClassDescriptionstatic class
static class
static class
-
Constructor Summary
ModifierConstructorDescriptionprotected
SpannerClient
(SpannerSettings settings) Constructs an instance of SpannerClient, using the given settings.protected
SpannerClient
(SpannerStub stub) -
Method Summary
Modifier and TypeMethodDescriptionboolean
awaitTermination
(long duration, TimeUnit unit) Creates multiple new sessions.batchCreateSessions
(DatabaseName database, int sessionCount) Creates multiple new sessions.batchCreateSessions
(String database, int sessionCount) Creates multiple new sessions.final com.google.api.gax.rpc.UnaryCallable<BatchCreateSessionsRequest,
BatchCreateSessionsResponse> Creates multiple new sessions.final com.google.api.gax.rpc.ServerStreamingCallable<BatchWriteRequest,
BatchWriteResponse> Batches the supplied mutation groups in a collection of efficient transactions.final Transaction
beginTransaction
(BeginTransactionRequest request) Begins a new transaction.final Transaction
beginTransaction
(SessionName session, TransactionOptions options) Begins a new transaction.final Transaction
beginTransaction
(String session, TransactionOptions options) Begins a new transaction.final com.google.api.gax.rpc.UnaryCallable<BeginTransactionRequest,
Transaction> Begins a new transaction.final void
close()
final CommitResponse
commit
(CommitRequest request) Commits a transaction.final CommitResponse
commit
(SessionName session, com.google.protobuf.ByteString transactionId, List<Mutation> mutations) Commits a transaction.final CommitResponse
commit
(SessionName session, TransactionOptions singleUseTransaction, List<Mutation> mutations) Commits a transaction.final CommitResponse
Commits a transaction.final CommitResponse
commit
(String session, TransactionOptions singleUseTransaction, List<Mutation> mutations) Commits a transaction.final com.google.api.gax.rpc.UnaryCallable<CommitRequest,
CommitResponse> Commits a transaction.static final SpannerClient
create()
Constructs an instance of SpannerClient with default settings.static final SpannerClient
create
(SpannerSettings settings) Constructs an instance of SpannerClient, using the given settings.static final SpannerClient
create
(SpannerStub stub) Constructs an instance of SpannerClient, using the given stub for making calls.final Session
createSession
(CreateSessionRequest request) Creates a new session.final Session
createSession
(DatabaseName database) Creates a new session.final Session
createSession
(String database) Creates a new session.final com.google.api.gax.rpc.UnaryCallable<CreateSessionRequest,
Session> Creates a new session.final void
deleteSession
(DeleteSessionRequest request) Ends a session, releasing server resources associated with it.final void
deleteSession
(SessionName name) Ends a session, releasing server resources associated with it.final void
deleteSession
(String name) Ends a session, releasing server resources associated with it.final com.google.api.gax.rpc.UnaryCallable<DeleteSessionRequest,
com.google.protobuf.Empty> Ends a session, releasing server resources associated with it.final ExecuteBatchDmlResponse
executeBatchDml
(ExecuteBatchDmlRequest request) Executes a batch of SQL DML statements.final com.google.api.gax.rpc.UnaryCallable<ExecuteBatchDmlRequest,
ExecuteBatchDmlResponse> Executes a batch of SQL DML statements.final ResultSet
executeSql
(ExecuteSqlRequest request) Executes an SQL statement, returning all results in a single reply.final com.google.api.gax.rpc.UnaryCallable<ExecuteSqlRequest,
ResultSet> Executes an SQL statement, returning all results in a single reply.final com.google.api.gax.rpc.ServerStreamingCallable<ExecuteSqlRequest,
PartialResultSet> Like [ExecuteSql][google.spanner.v1.Spanner.ExecuteSql], except returns the result set as a stream.final Session
getSession
(GetSessionRequest request) Gets a session.final Session
getSession
(SessionName name) Gets a session.final Session
getSession
(String name) Gets a session.final com.google.api.gax.rpc.UnaryCallable<GetSessionRequest,
Session> Gets a session.final SpannerSettings
getStub()
boolean
boolean
listSessions
(DatabaseName database) Lists all sessions in a given database.listSessions
(ListSessionsRequest request) Lists all sessions in a given database.listSessions
(String database) Lists all sessions in a given database.final com.google.api.gax.rpc.UnaryCallable<ListSessionsRequest,
ListSessionsResponse> Lists all sessions in a given database.final com.google.api.gax.rpc.UnaryCallable<ListSessionsRequest,
SpannerClient.ListSessionsPagedResponse> Lists all sessions in a given database.final PartitionResponse
partitionQuery
(PartitionQueryRequest request) Creates a set of partition tokens that can be used to execute a query operation in parallel.final com.google.api.gax.rpc.UnaryCallable<PartitionQueryRequest,
PartitionResponse> Creates a set of partition tokens that can be used to execute a query operation in parallel.final PartitionResponse
partitionRead
(PartitionReadRequest request) Creates a set of partition tokens that can be used to execute a read operation in parallel.final com.google.api.gax.rpc.UnaryCallable<PartitionReadRequest,
PartitionResponse> Creates a set of partition tokens that can be used to execute a read operation in parallel.final ResultSet
read
(ReadRequest request) Reads rows from the database using key lookups and scans, as a simple key/value style alternative to [ExecuteSql][google.spanner.v1.Spanner.ExecuteSql].final com.google.api.gax.rpc.UnaryCallable<ReadRequest,
ResultSet> Reads rows from the database using key lookups and scans, as a simple key/value style alternative to [ExecuteSql][google.spanner.v1.Spanner.ExecuteSql].final void
rollback
(RollbackRequest request) Rolls back a transaction, releasing any locks it holds.final void
rollback
(SessionName session, com.google.protobuf.ByteString transactionId) Rolls back a transaction, releasing any locks it holds.final void
Rolls back a transaction, releasing any locks it holds.final com.google.api.gax.rpc.UnaryCallable<RollbackRequest,
com.google.protobuf.Empty> Rolls back a transaction, releasing any locks it holds.void
shutdown()
void
final com.google.api.gax.rpc.ServerStreamingCallable<ReadRequest,
PartialResultSet> Like [Read][google.spanner.v1.Spanner.Read], except returns the result set as a stream.
-
Constructor Details
-
SpannerClient
Constructs an instance of SpannerClient, using the given settings. This is protected so that it is easy to make a subclass, but otherwise, the static factory methods should be preferred.- Throws:
IOException
-
SpannerClient
-
-
Method Details
-
create
Constructs an instance of SpannerClient with default settings.- Throws:
IOException
-
create
Constructs an instance of SpannerClient, using the given settings. The channels are created based on the settings passed in, or defaults for any settings that are not set.- Throws:
IOException
-
create
Constructs an instance of SpannerClient, using the given stub for making calls. This is for advanced usage - prefer using create(SpannerSettings). -
getSettings
-
getStub
-
createSession
Creates a new session. A session can be used to perform transactions that read and/or modify data in a Cloud Spanner database. Sessions are meant to be reused for many consecutive transactions.Sessions can only execute one transaction at a time. To execute multiple concurrent read-write/write-only transactions, create multiple sessions. Note that standalone reads and queries use a transaction internally, and count toward the one transaction limit.
Active sessions use additional server resources, so it is a good idea to delete idle and unneeded sessions. Aside from explicit deletes, Cloud Spanner may delete sessions for which no operations are sent for more than an hour. If a session is deleted, requests to it return `NOT_FOUND`.
Idle sessions can be kept alive by sending a trivial SQL query periodically, e.g., `"SELECT 1"`.
Sample code:
// This snippet has been automatically generated and should be regarded as a code template only. // It will require modifications to work: // - It may require correct/in-range values for request initialization. // - It may require specifying regional endpoints when creating the service client as shown in // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library try (SpannerClient spannerClient = SpannerClient.create()) { DatabaseName database = DatabaseName.of("[PROJECT]", "[INSTANCE]", "[DATABASE]"); Session response = spannerClient.createSession(database); }
- Parameters:
database
- Required. The database in which the new session is created.- Throws:
com.google.api.gax.rpc.ApiException
- if the remote call fails
-
createSession
Creates a new session. A session can be used to perform transactions that read and/or modify data in a Cloud Spanner database. Sessions are meant to be reused for many consecutive transactions.Sessions can only execute one transaction at a time. To execute multiple concurrent read-write/write-only transactions, create multiple sessions. Note that standalone reads and queries use a transaction internally, and count toward the one transaction limit.
Active sessions use additional server resources, so it is a good idea to delete idle and unneeded sessions. Aside from explicit deletes, Cloud Spanner may delete sessions for which no operations are sent for more than an hour. If a session is deleted, requests to it return `NOT_FOUND`.
Idle sessions can be kept alive by sending a trivial SQL query periodically, e.g., `"SELECT 1"`.
Sample code:
// This snippet has been automatically generated and should be regarded as a code template only. // It will require modifications to work: // - It may require correct/in-range values for request initialization. // - It may require specifying regional endpoints when creating the service client as shown in // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library try (SpannerClient spannerClient = SpannerClient.create()) { String database = DatabaseName.of("[PROJECT]", "[INSTANCE]", "[DATABASE]").toString(); Session response = spannerClient.createSession(database); }
- Parameters:
database
- Required. The database in which the new session is created.- Throws:
com.google.api.gax.rpc.ApiException
- if the remote call fails
-
createSession
Creates a new session. A session can be used to perform transactions that read and/or modify data in a Cloud Spanner database. Sessions are meant to be reused for many consecutive transactions.Sessions can only execute one transaction at a time. To execute multiple concurrent read-write/write-only transactions, create multiple sessions. Note that standalone reads and queries use a transaction internally, and count toward the one transaction limit.
Active sessions use additional server resources, so it is a good idea to delete idle and unneeded sessions. Aside from explicit deletes, Cloud Spanner may delete sessions for which no operations are sent for more than an hour. If a session is deleted, requests to it return `NOT_FOUND`.
Idle sessions can be kept alive by sending a trivial SQL query periodically, e.g., `"SELECT 1"`.
Sample code:
// This snippet has been automatically generated and should be regarded as a code template only. // It will require modifications to work: // - It may require correct/in-range values for request initialization. // - It may require specifying regional endpoints when creating the service client as shown in // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library try (SpannerClient spannerClient = SpannerClient.create()) { CreateSessionRequest request = CreateSessionRequest.newBuilder() .setDatabase(DatabaseName.of("[PROJECT]", "[INSTANCE]", "[DATABASE]").toString()) .setSession(Session.newBuilder().build()) .build(); Session response = spannerClient.createSession(request); }
- Parameters:
request
- The request object containing all of the parameters for the API call.- Throws:
com.google.api.gax.rpc.ApiException
- if the remote call fails
-
createSessionCallable
public final com.google.api.gax.rpc.UnaryCallable<CreateSessionRequest,Session> createSessionCallable()Creates a new session. A session can be used to perform transactions that read and/or modify data in a Cloud Spanner database. Sessions are meant to be reused for many consecutive transactions.Sessions can only execute one transaction at a time. To execute multiple concurrent read-write/write-only transactions, create multiple sessions. Note that standalone reads and queries use a transaction internally, and count toward the one transaction limit.
Active sessions use additional server resources, so it is a good idea to delete idle and unneeded sessions. Aside from explicit deletes, Cloud Spanner may delete sessions for which no operations are sent for more than an hour. If a session is deleted, requests to it return `NOT_FOUND`.
Idle sessions can be kept alive by sending a trivial SQL query periodically, e.g., `"SELECT 1"`.
Sample code:
// This snippet has been automatically generated and should be regarded as a code template only. // It will require modifications to work: // - It may require correct/in-range values for request initialization. // - It may require specifying regional endpoints when creating the service client as shown in // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library try (SpannerClient spannerClient = SpannerClient.create()) { CreateSessionRequest request = CreateSessionRequest.newBuilder() .setDatabase(DatabaseName.of("[PROJECT]", "[INSTANCE]", "[DATABASE]").toString()) .setSession(Session.newBuilder().build()) .build(); ApiFuture<Session> future = spannerClient.createSessionCallable().futureCall(request); // Do something. Session response = future.get(); }
-
batchCreateSessions
public final BatchCreateSessionsResponse batchCreateSessions(DatabaseName database, int sessionCount) Creates multiple new sessions.This API can be used to initialize a session cache on the clients. See https://goo.gl/TgSFN2 for best practices on session cache management.
Sample code:
// This snippet has been automatically generated and should be regarded as a code template only. // It will require modifications to work: // - It may require correct/in-range values for request initialization. // - It may require specifying regional endpoints when creating the service client as shown in // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library try (SpannerClient spannerClient = SpannerClient.create()) { DatabaseName database = DatabaseName.of("[PROJECT]", "[INSTANCE]", "[DATABASE]"); int sessionCount = 185691686; BatchCreateSessionsResponse response = spannerClient.batchCreateSessions(database, sessionCount); }
- Parameters:
database
- Required. The database in which the new sessions are created.sessionCount
- Required. The number of sessions to be created in this batch call. The API may return fewer than the requested number of sessions. If a specific number of sessions are desired, the client can make additional calls to BatchCreateSessions (adjusting [session_count][google.spanner.v1.BatchCreateSessionsRequest.session_count] as necessary).- Throws:
com.google.api.gax.rpc.ApiException
- if the remote call fails
-
batchCreateSessions
Creates multiple new sessions.This API can be used to initialize a session cache on the clients. See https://goo.gl/TgSFN2 for best practices on session cache management.
Sample code:
// This snippet has been automatically generated and should be regarded as a code template only. // It will require modifications to work: // - It may require correct/in-range values for request initialization. // - It may require specifying regional endpoints when creating the service client as shown in // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library try (SpannerClient spannerClient = SpannerClient.create()) { String database = DatabaseName.of("[PROJECT]", "[INSTANCE]", "[DATABASE]").toString(); int sessionCount = 185691686; BatchCreateSessionsResponse response = spannerClient.batchCreateSessions(database, sessionCount); }
- Parameters:
database
- Required. The database in which the new sessions are created.sessionCount
- Required. The number of sessions to be created in this batch call. The API may return fewer than the requested number of sessions. If a specific number of sessions are desired, the client can make additional calls to BatchCreateSessions (adjusting [session_count][google.spanner.v1.BatchCreateSessionsRequest.session_count] as necessary).- Throws:
com.google.api.gax.rpc.ApiException
- if the remote call fails
-
batchCreateSessions
Creates multiple new sessions.This API can be used to initialize a session cache on the clients. See https://goo.gl/TgSFN2 for best practices on session cache management.
Sample code:
// This snippet has been automatically generated and should be regarded as a code template only. // It will require modifications to work: // - It may require correct/in-range values for request initialization. // - It may require specifying regional endpoints when creating the service client as shown in // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library try (SpannerClient spannerClient = SpannerClient.create()) { BatchCreateSessionsRequest request = BatchCreateSessionsRequest.newBuilder() .setDatabase(DatabaseName.of("[PROJECT]", "[INSTANCE]", "[DATABASE]").toString()) .setSessionTemplate(Session.newBuilder().build()) .setSessionCount(185691686) .build(); BatchCreateSessionsResponse response = spannerClient.batchCreateSessions(request); }
- Parameters:
request
- The request object containing all of the parameters for the API call.- Throws:
com.google.api.gax.rpc.ApiException
- if the remote call fails
-
batchCreateSessionsCallable
public final com.google.api.gax.rpc.UnaryCallable<BatchCreateSessionsRequest,BatchCreateSessionsResponse> batchCreateSessionsCallable()Creates multiple new sessions.This API can be used to initialize a session cache on the clients. See https://goo.gl/TgSFN2 for best practices on session cache management.
Sample code:
// This snippet has been automatically generated and should be regarded as a code template only. // It will require modifications to work: // - It may require correct/in-range values for request initialization. // - It may require specifying regional endpoints when creating the service client as shown in // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library try (SpannerClient spannerClient = SpannerClient.create()) { BatchCreateSessionsRequest request = BatchCreateSessionsRequest.newBuilder() .setDatabase(DatabaseName.of("[PROJECT]", "[INSTANCE]", "[DATABASE]").toString()) .setSessionTemplate(Session.newBuilder().build()) .setSessionCount(185691686) .build(); ApiFuture<BatchCreateSessionsResponse> future = spannerClient.batchCreateSessionsCallable().futureCall(request); // Do something. BatchCreateSessionsResponse response = future.get(); }
-
getSession
Gets a session. Returns `NOT_FOUND` if the session does not exist. This is mainly useful for determining whether a session is still alive.Sample code:
// This snippet has been automatically generated and should be regarded as a code template only. // It will require modifications to work: // - It may require correct/in-range values for request initialization. // - It may require specifying regional endpoints when creating the service client as shown in // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library try (SpannerClient spannerClient = SpannerClient.create()) { SessionName name = SessionName.of("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"); Session response = spannerClient.getSession(name); }
- Parameters:
name
- Required. The name of the session to retrieve.- Throws:
com.google.api.gax.rpc.ApiException
- if the remote call fails
-
getSession
Gets a session. Returns `NOT_FOUND` if the session does not exist. This is mainly useful for determining whether a session is still alive.Sample code:
// This snippet has been automatically generated and should be regarded as a code template only. // It will require modifications to work: // - It may require correct/in-range values for request initialization. // - It may require specifying regional endpoints when creating the service client as shown in // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library try (SpannerClient spannerClient = SpannerClient.create()) { String name = SessionName.of("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]").toString(); Session response = spannerClient.getSession(name); }
- Parameters:
name
- Required. The name of the session to retrieve.- Throws:
com.google.api.gax.rpc.ApiException
- if the remote call fails
-
getSession
Gets a session. Returns `NOT_FOUND` if the session does not exist. This is mainly useful for determining whether a session is still alive.Sample code:
// This snippet has been automatically generated and should be regarded as a code template only. // It will require modifications to work: // - It may require correct/in-range values for request initialization. // - It may require specifying regional endpoints when creating the service client as shown in // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library try (SpannerClient spannerClient = SpannerClient.create()) { GetSessionRequest request = GetSessionRequest.newBuilder() .setName( SessionName.of("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]").toString()) .build(); Session response = spannerClient.getSession(request); }
- Parameters:
request
- The request object containing all of the parameters for the API call.- Throws:
com.google.api.gax.rpc.ApiException
- if the remote call fails
-
getSessionCallable
Gets a session. Returns `NOT_FOUND` if the session does not exist. This is mainly useful for determining whether a session is still alive.Sample code:
// This snippet has been automatically generated and should be regarded as a code template only. // It will require modifications to work: // - It may require correct/in-range values for request initialization. // - It may require specifying regional endpoints when creating the service client as shown in // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library try (SpannerClient spannerClient = SpannerClient.create()) { GetSessionRequest request = GetSessionRequest.newBuilder() .setName( SessionName.of("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]").toString()) .build(); ApiFuture<Session> future = spannerClient.getSessionCallable().futureCall(request); // Do something. Session response = future.get(); }
-
listSessions
Lists all sessions in a given database.Sample code:
// This snippet has been automatically generated and should be regarded as a code template only. // It will require modifications to work: // - It may require correct/in-range values for request initialization. // - It may require specifying regional endpoints when creating the service client as shown in // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library try (SpannerClient spannerClient = SpannerClient.create()) { DatabaseName database = DatabaseName.of("[PROJECT]", "[INSTANCE]", "[DATABASE]"); for (Session element : spannerClient.listSessions(database).iterateAll()) { // doThingsWith(element); } }
- Parameters:
database
- Required. The database in which to list sessions.- Throws:
com.google.api.gax.rpc.ApiException
- if the remote call fails
-
listSessions
Lists all sessions in a given database.Sample code:
// This snippet has been automatically generated and should be regarded as a code template only. // It will require modifications to work: // - It may require correct/in-range values for request initialization. // - It may require specifying regional endpoints when creating the service client as shown in // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library try (SpannerClient spannerClient = SpannerClient.create()) { String database = DatabaseName.of("[PROJECT]", "[INSTANCE]", "[DATABASE]").toString(); for (Session element : spannerClient.listSessions(database).iterateAll()) { // doThingsWith(element); } }
- Parameters:
database
- Required. The database in which to list sessions.- Throws:
com.google.api.gax.rpc.ApiException
- if the remote call fails
-
listSessions
Lists all sessions in a given database.Sample code:
// This snippet has been automatically generated and should be regarded as a code template only. // It will require modifications to work: // - It may require correct/in-range values for request initialization. // - It may require specifying regional endpoints when creating the service client as shown in // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library try (SpannerClient spannerClient = SpannerClient.create()) { ListSessionsRequest request = ListSessionsRequest.newBuilder() .setDatabase(DatabaseName.of("[PROJECT]", "[INSTANCE]", "[DATABASE]").toString()) .setPageSize(883849137) .setPageToken("pageToken873572522") .setFilter("filter-1274492040") .build(); for (Session element : spannerClient.listSessions(request).iterateAll()) { // doThingsWith(element); } }
- Parameters:
request
- The request object containing all of the parameters for the API call.- Throws:
com.google.api.gax.rpc.ApiException
- if the remote call fails
-
listSessionsPagedCallable
public final com.google.api.gax.rpc.UnaryCallable<ListSessionsRequest,SpannerClient.ListSessionsPagedResponse> listSessionsPagedCallable()Lists all sessions in a given database.Sample code:
// This snippet has been automatically generated and should be regarded as a code template only. // It will require modifications to work: // - It may require correct/in-range values for request initialization. // - It may require specifying regional endpoints when creating the service client as shown in // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library try (SpannerClient spannerClient = SpannerClient.create()) { ListSessionsRequest request = ListSessionsRequest.newBuilder() .setDatabase(DatabaseName.of("[PROJECT]", "[INSTANCE]", "[DATABASE]").toString()) .setPageSize(883849137) .setPageToken("pageToken873572522") .setFilter("filter-1274492040") .build(); ApiFuture<Session> future = spannerClient.listSessionsPagedCallable().futureCall(request); // Do something. for (Session element : future.get().iterateAll()) { // doThingsWith(element); } }
-
listSessionsCallable
public final com.google.api.gax.rpc.UnaryCallable<ListSessionsRequest,ListSessionsResponse> listSessionsCallable()Lists all sessions in a given database.Sample code:
// This snippet has been automatically generated and should be regarded as a code template only. // It will require modifications to work: // - It may require correct/in-range values for request initialization. // - It may require specifying regional endpoints when creating the service client as shown in // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library try (SpannerClient spannerClient = SpannerClient.create()) { ListSessionsRequest request = ListSessionsRequest.newBuilder() .setDatabase(DatabaseName.of("[PROJECT]", "[INSTANCE]", "[DATABASE]").toString()) .setPageSize(883849137) .setPageToken("pageToken873572522") .setFilter("filter-1274492040") .build(); while (true) { ListSessionsResponse response = spannerClient.listSessionsCallable().call(request); for (Session element : response.getSessionsList()) { // doThingsWith(element); } String nextPageToken = response.getNextPageToken(); if (!Strings.isNullOrEmpty(nextPageToken)) { request = request.toBuilder().setPageToken(nextPageToken).build(); } else { break; } } }
-
deleteSession
Ends a session, releasing server resources associated with it. This will asynchronously trigger cancellation of any operations that are running with this session.Sample code:
// This snippet has been automatically generated and should be regarded as a code template only. // It will require modifications to work: // - It may require correct/in-range values for request initialization. // - It may require specifying regional endpoints when creating the service client as shown in // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library try (SpannerClient spannerClient = SpannerClient.create()) { SessionName name = SessionName.of("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"); spannerClient.deleteSession(name); }
- Parameters:
name
- Required. The name of the session to delete.- Throws:
com.google.api.gax.rpc.ApiException
- if the remote call fails
-
deleteSession
Ends a session, releasing server resources associated with it. This will asynchronously trigger cancellation of any operations that are running with this session.Sample code:
// This snippet has been automatically generated and should be regarded as a code template only. // It will require modifications to work: // - It may require correct/in-range values for request initialization. // - It may require specifying regional endpoints when creating the service client as shown in // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library try (SpannerClient spannerClient = SpannerClient.create()) { String name = SessionName.of("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]").toString(); spannerClient.deleteSession(name); }
- Parameters:
name
- Required. The name of the session to delete.- Throws:
com.google.api.gax.rpc.ApiException
- if the remote call fails
-
deleteSession
Ends a session, releasing server resources associated with it. This will asynchronously trigger cancellation of any operations that are running with this session.Sample code:
// This snippet has been automatically generated and should be regarded as a code template only. // It will require modifications to work: // - It may require correct/in-range values for request initialization. // - It may require specifying regional endpoints when creating the service client as shown in // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library try (SpannerClient spannerClient = SpannerClient.create()) { DeleteSessionRequest request = DeleteSessionRequest.newBuilder() .setName( SessionName.of("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]").toString()) .build(); spannerClient.deleteSession(request); }
- Parameters:
request
- The request object containing all of the parameters for the API call.- Throws:
com.google.api.gax.rpc.ApiException
- if the remote call fails
-
deleteSessionCallable
public final com.google.api.gax.rpc.UnaryCallable<DeleteSessionRequest,com.google.protobuf.Empty> deleteSessionCallable()Ends a session, releasing server resources associated with it. This will asynchronously trigger cancellation of any operations that are running with this session.Sample code:
// This snippet has been automatically generated and should be regarded as a code template only. // It will require modifications to work: // - It may require correct/in-range values for request initialization. // - It may require specifying regional endpoints when creating the service client as shown in // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library try (SpannerClient spannerClient = SpannerClient.create()) { DeleteSessionRequest request = DeleteSessionRequest.newBuilder() .setName( SessionName.of("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]").toString()) .build(); ApiFuture<Empty> future = spannerClient.deleteSessionCallable().futureCall(request); // Do something. future.get(); }
-
executeSql
Executes an SQL statement, returning all results in a single reply. This method cannot be used to return a result set larger than 10 MiB; if the query yields more data than that, the query fails with a `FAILED_PRECONDITION` error.Operations inside read-write transactions might return `ABORTED`. If this occurs, the application should restart the transaction from the beginning. See [Transaction][google.spanner.v1.Transaction] for more details.
Larger result sets can be fetched in streaming fashion by calling [ExecuteStreamingSql][google.spanner.v1.Spanner.ExecuteStreamingSql] instead.
Sample code:
// This snippet has been automatically generated and should be regarded as a code template only. // It will require modifications to work: // - It may require correct/in-range values for request initialization. // - It may require specifying regional endpoints when creating the service client as shown in // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library try (SpannerClient spannerClient = SpannerClient.create()) { ExecuteSqlRequest request = ExecuteSqlRequest.newBuilder() .setSession( SessionName.of("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]").toString()) .setTransaction(TransactionSelector.newBuilder().build()) .setSql("sql114126") .setParams(Struct.newBuilder().build()) .putAllParamTypes(new HashMap<String, Type>()) .setResumeToken(ByteString.EMPTY) .setPartitionToken(ByteString.EMPTY) .setSeqno(109325920) .setQueryOptions(ExecuteSqlRequest.QueryOptions.newBuilder().build()) .setRequestOptions(RequestOptions.newBuilder().build()) .setDirectedReadOptions(DirectedReadOptions.newBuilder().build()) .setDataBoostEnabled(true) .build(); ResultSet response = spannerClient.executeSql(request); }
- Parameters:
request
- The request object containing all of the parameters for the API call.- Throws:
com.google.api.gax.rpc.ApiException
- if the remote call fails
-
executeSqlCallable
Executes an SQL statement, returning all results in a single reply. This method cannot be used to return a result set larger than 10 MiB; if the query yields more data than that, the query fails with a `FAILED_PRECONDITION` error.Operations inside read-write transactions might return `ABORTED`. If this occurs, the application should restart the transaction from the beginning. See [Transaction][google.spanner.v1.Transaction] for more details.
Larger result sets can be fetched in streaming fashion by calling [ExecuteStreamingSql][google.spanner.v1.Spanner.ExecuteStreamingSql] instead.
Sample code:
// This snippet has been automatically generated and should be regarded as a code template only. // It will require modifications to work: // - It may require correct/in-range values for request initialization. // - It may require specifying regional endpoints when creating the service client as shown in // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library try (SpannerClient spannerClient = SpannerClient.create()) { ExecuteSqlRequest request = ExecuteSqlRequest.newBuilder() .setSession( SessionName.of("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]").toString()) .setTransaction(TransactionSelector.newBuilder().build()) .setSql("sql114126") .setParams(Struct.newBuilder().build()) .putAllParamTypes(new HashMap<String, Type>()) .setResumeToken(ByteString.EMPTY) .setPartitionToken(ByteString.EMPTY) .setSeqno(109325920) .setQueryOptions(ExecuteSqlRequest.QueryOptions.newBuilder().build()) .setRequestOptions(RequestOptions.newBuilder().build()) .setDirectedReadOptions(DirectedReadOptions.newBuilder().build()) .setDataBoostEnabled(true) .build(); ApiFuture<ResultSet> future = spannerClient.executeSqlCallable().futureCall(request); // Do something. ResultSet response = future.get(); }
-
executeStreamingSqlCallable
public final com.google.api.gax.rpc.ServerStreamingCallable<ExecuteSqlRequest,PartialResultSet> executeStreamingSqlCallable()Like [ExecuteSql][google.spanner.v1.Spanner.ExecuteSql], except returns the result set as a stream. Unlike [ExecuteSql][google.spanner.v1.Spanner.ExecuteSql], there is no limit on the size of the returned result set. However, no individual row in the result set can exceed 100 MiB, and no column value can exceed 10 MiB.Sample code:
// This snippet has been automatically generated and should be regarded as a code template only. // It will require modifications to work: // - It may require correct/in-range values for request initialization. // - It may require specifying regional endpoints when creating the service client as shown in // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library try (SpannerClient spannerClient = SpannerClient.create()) { ExecuteSqlRequest request = ExecuteSqlRequest.newBuilder() .setSession( SessionName.of("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]").toString()) .setTransaction(TransactionSelector.newBuilder().build()) .setSql("sql114126") .setParams(Struct.newBuilder().build()) .putAllParamTypes(new HashMap<String, Type>()) .setResumeToken(ByteString.EMPTY) .setPartitionToken(ByteString.EMPTY) .setSeqno(109325920) .setQueryOptions(ExecuteSqlRequest.QueryOptions.newBuilder().build()) .setRequestOptions(RequestOptions.newBuilder().build()) .setDirectedReadOptions(DirectedReadOptions.newBuilder().build()) .setDataBoostEnabled(true) .build(); ServerStream<PartialResultSet> stream = spannerClient.executeStreamingSqlCallable().call(request); for (PartialResultSet response : stream) { // Do something when a response is received. } }
-
executeBatchDml
Executes a batch of SQL DML statements. This method allows many statements to be run with lower latency than submitting them sequentially with [ExecuteSql][google.spanner.v1.Spanner.ExecuteSql].Statements are executed in sequential order. A request can succeed even if a statement fails. The [ExecuteBatchDmlResponse.status][google.spanner.v1.ExecuteBatchDmlResponse.status] field in the response provides information about the statement that failed. Clients must inspect this field to determine whether an error occurred.
Execution stops after the first failed statement; the remaining statements are not executed.
Sample code:
// This snippet has been automatically generated and should be regarded as a code template only. // It will require modifications to work: // - It may require correct/in-range values for request initialization. // - It may require specifying regional endpoints when creating the service client as shown in // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library try (SpannerClient spannerClient = SpannerClient.create()) { ExecuteBatchDmlRequest request = ExecuteBatchDmlRequest.newBuilder() .setSession( SessionName.of("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]").toString()) .setTransaction(TransactionSelector.newBuilder().build()) .addAllStatements(new ArrayList<ExecuteBatchDmlRequest.Statement>()) .setSeqno(109325920) .setRequestOptions(RequestOptions.newBuilder().build()) .build(); ExecuteBatchDmlResponse response = spannerClient.executeBatchDml(request); }
- Parameters:
request
- The request object containing all of the parameters for the API call.- Throws:
com.google.api.gax.rpc.ApiException
- if the remote call fails
-
executeBatchDmlCallable
public final com.google.api.gax.rpc.UnaryCallable<ExecuteBatchDmlRequest,ExecuteBatchDmlResponse> executeBatchDmlCallable()Executes a batch of SQL DML statements. This method allows many statements to be run with lower latency than submitting them sequentially with [ExecuteSql][google.spanner.v1.Spanner.ExecuteSql].Statements are executed in sequential order. A request can succeed even if a statement fails. The [ExecuteBatchDmlResponse.status][google.spanner.v1.ExecuteBatchDmlResponse.status] field in the response provides information about the statement that failed. Clients must inspect this field to determine whether an error occurred.
Execution stops after the first failed statement; the remaining statements are not executed.
Sample code:
// This snippet has been automatically generated and should be regarded as a code template only. // It will require modifications to work: // - It may require correct/in-range values for request initialization. // - It may require specifying regional endpoints when creating the service client as shown in // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library try (SpannerClient spannerClient = SpannerClient.create()) { ExecuteBatchDmlRequest request = ExecuteBatchDmlRequest.newBuilder() .setSession( SessionName.of("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]").toString()) .setTransaction(TransactionSelector.newBuilder().build()) .addAllStatements(new ArrayList<ExecuteBatchDmlRequest.Statement>()) .setSeqno(109325920) .setRequestOptions(RequestOptions.newBuilder().build()) .build(); ApiFuture<ExecuteBatchDmlResponse> future = spannerClient.executeBatchDmlCallable().futureCall(request); // Do something. ExecuteBatchDmlResponse response = future.get(); }
-
read
Reads rows from the database using key lookups and scans, as a simple key/value style alternative to [ExecuteSql][google.spanner.v1.Spanner.ExecuteSql]. This method cannot be used to return a result set larger than 10 MiB; if the read matches more data than that, the read fails with a `FAILED_PRECONDITION` error.Reads inside read-write transactions might return `ABORTED`. If this occurs, the application should restart the transaction from the beginning. See [Transaction][google.spanner.v1.Transaction] for more details.
Larger result sets can be yielded in streaming fashion by calling [StreamingRead][google.spanner.v1.Spanner.StreamingRead] instead.
Sample code:
// This snippet has been automatically generated and should be regarded as a code template only. // It will require modifications to work: // - It may require correct/in-range values for request initialization. // - It may require specifying regional endpoints when creating the service client as shown in // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library try (SpannerClient spannerClient = SpannerClient.create()) { ReadRequest request = ReadRequest.newBuilder() .setSession( SessionName.of("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]").toString()) .setTransaction(TransactionSelector.newBuilder().build()) .setTable("table110115790") .setIndex("index100346066") .addAllColumns(new ArrayList<String>()) .setKeySet(KeySet.newBuilder().build()) .setLimit(102976443) .setResumeToken(ByteString.EMPTY) .setPartitionToken(ByteString.EMPTY) .setRequestOptions(RequestOptions.newBuilder().build()) .setDirectedReadOptions(DirectedReadOptions.newBuilder().build()) .setDataBoostEnabled(true) .build(); ResultSet response = spannerClient.read(request); }
- Parameters:
request
- The request object containing all of the parameters for the API call.- Throws:
com.google.api.gax.rpc.ApiException
- if the remote call fails
-
readCallable
Reads rows from the database using key lookups and scans, as a simple key/value style alternative to [ExecuteSql][google.spanner.v1.Spanner.ExecuteSql]. This method cannot be used to return a result set larger than 10 MiB; if the read matches more data than that, the read fails with a `FAILED_PRECONDITION` error.Reads inside read-write transactions might return `ABORTED`. If this occurs, the application should restart the transaction from the beginning. See [Transaction][google.spanner.v1.Transaction] for more details.
Larger result sets can be yielded in streaming fashion by calling [StreamingRead][google.spanner.v1.Spanner.StreamingRead] instead.
Sample code:
// This snippet has been automatically generated and should be regarded as a code template only. // It will require modifications to work: // - It may require correct/in-range values for request initialization. // - It may require specifying regional endpoints when creating the service client as shown in // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library try (SpannerClient spannerClient = SpannerClient.create()) { ReadRequest request = ReadRequest.newBuilder() .setSession( SessionName.of("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]").toString()) .setTransaction(TransactionSelector.newBuilder().build()) .setTable("table110115790") .setIndex("index100346066") .addAllColumns(new ArrayList<String>()) .setKeySet(KeySet.newBuilder().build()) .setLimit(102976443) .setResumeToken(ByteString.EMPTY) .setPartitionToken(ByteString.EMPTY) .setRequestOptions(RequestOptions.newBuilder().build()) .setDirectedReadOptions(DirectedReadOptions.newBuilder().build()) .setDataBoostEnabled(true) .build(); ApiFuture<ResultSet> future = spannerClient.readCallable().futureCall(request); // Do something. ResultSet response = future.get(); }
-
streamingReadCallable
public final com.google.api.gax.rpc.ServerStreamingCallable<ReadRequest,PartialResultSet> streamingReadCallable()Like [Read][google.spanner.v1.Spanner.Read], except returns the result set as a stream. Unlike [Read][google.spanner.v1.Spanner.Read], there is no limit on the size of the returned result set. However, no individual row in the result set can exceed 100 MiB, and no column value can exceed 10 MiB.Sample code:
// This snippet has been automatically generated and should be regarded as a code template only. // It will require modifications to work: // - It may require correct/in-range values for request initialization. // - It may require specifying regional endpoints when creating the service client as shown in // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library try (SpannerClient spannerClient = SpannerClient.create()) { ReadRequest request = ReadRequest.newBuilder() .setSession( SessionName.of("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]").toString()) .setTransaction(TransactionSelector.newBuilder().build()) .setTable("table110115790") .setIndex("index100346066") .addAllColumns(new ArrayList<String>()) .setKeySet(KeySet.newBuilder().build()) .setLimit(102976443) .setResumeToken(ByteString.EMPTY) .setPartitionToken(ByteString.EMPTY) .setRequestOptions(RequestOptions.newBuilder().build()) .setDirectedReadOptions(DirectedReadOptions.newBuilder().build()) .setDataBoostEnabled(true) .build(); ServerStream<PartialResultSet> stream = spannerClient.streamingReadCallable().call(request); for (PartialResultSet response : stream) { // Do something when a response is received. } }
-
beginTransaction
Begins a new transaction. This step can often be skipped: [Read][google.spanner.v1.Spanner.Read], [ExecuteSql][google.spanner.v1.Spanner.ExecuteSql] and [Commit][google.spanner.v1.Spanner.Commit] can begin a new transaction as a side-effect.Sample code:
// This snippet has been automatically generated and should be regarded as a code template only. // It will require modifications to work: // - It may require correct/in-range values for request initialization. // - It may require specifying regional endpoints when creating the service client as shown in // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library try (SpannerClient spannerClient = SpannerClient.create()) { SessionName session = SessionName.of("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"); TransactionOptions options = TransactionOptions.newBuilder().build(); Transaction response = spannerClient.beginTransaction(session, options); }
- Parameters:
session
- Required. The session in which the transaction runs.options
- Required. Options for the new transaction.- Throws:
com.google.api.gax.rpc.ApiException
- if the remote call fails
-
beginTransaction
Begins a new transaction. This step can often be skipped: [Read][google.spanner.v1.Spanner.Read], [ExecuteSql][google.spanner.v1.Spanner.ExecuteSql] and [Commit][google.spanner.v1.Spanner.Commit] can begin a new transaction as a side-effect.Sample code:
// This snippet has been automatically generated and should be regarded as a code template only. // It will require modifications to work: // - It may require correct/in-range values for request initialization. // - It may require specifying regional endpoints when creating the service client as shown in // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library try (SpannerClient spannerClient = SpannerClient.create()) { String session = SessionName.of("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]").toString(); TransactionOptions options = TransactionOptions.newBuilder().build(); Transaction response = spannerClient.beginTransaction(session, options); }
- Parameters:
session
- Required. The session in which the transaction runs.options
- Required. Options for the new transaction.- Throws:
com.google.api.gax.rpc.ApiException
- if the remote call fails
-
beginTransaction
Begins a new transaction. This step can often be skipped: [Read][google.spanner.v1.Spanner.Read], [ExecuteSql][google.spanner.v1.Spanner.ExecuteSql] and [Commit][google.spanner.v1.Spanner.Commit] can begin a new transaction as a side-effect.Sample code:
// This snippet has been automatically generated and should be regarded as a code template only. // It will require modifications to work: // - It may require correct/in-range values for request initialization. // - It may require specifying regional endpoints when creating the service client as shown in // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library try (SpannerClient spannerClient = SpannerClient.create()) { BeginTransactionRequest request = BeginTransactionRequest.newBuilder() .setSession( SessionName.of("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]").toString()) .setOptions(TransactionOptions.newBuilder().build()) .setRequestOptions(RequestOptions.newBuilder().build()) .build(); Transaction response = spannerClient.beginTransaction(request); }
- Parameters:
request
- The request object containing all of the parameters for the API call.- Throws:
com.google.api.gax.rpc.ApiException
- if the remote call fails
-
beginTransactionCallable
public final com.google.api.gax.rpc.UnaryCallable<BeginTransactionRequest,Transaction> beginTransactionCallable()Begins a new transaction. This step can often be skipped: [Read][google.spanner.v1.Spanner.Read], [ExecuteSql][google.spanner.v1.Spanner.ExecuteSql] and [Commit][google.spanner.v1.Spanner.Commit] can begin a new transaction as a side-effect.Sample code:
// This snippet has been automatically generated and should be regarded as a code template only. // It will require modifications to work: // - It may require correct/in-range values for request initialization. // - It may require specifying regional endpoints when creating the service client as shown in // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library try (SpannerClient spannerClient = SpannerClient.create()) { BeginTransactionRequest request = BeginTransactionRequest.newBuilder() .setSession( SessionName.of("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]").toString()) .setOptions(TransactionOptions.newBuilder().build()) .setRequestOptions(RequestOptions.newBuilder().build()) .build(); ApiFuture<Transaction> future = spannerClient.beginTransactionCallable().futureCall(request); // Do something. Transaction response = future.get(); }
-
commit
public final CommitResponse commit(SessionName session, com.google.protobuf.ByteString transactionId, List<Mutation> mutations) Commits a transaction. The request includes the mutations to be applied to rows in the database.`Commit` might return an `ABORTED` error. This can occur at any time; commonly, the cause is conflicts with concurrent transactions. However, it can also happen for a variety of other reasons. If `Commit` returns `ABORTED`, the caller should re-attempt the transaction from the beginning, re-using the same session.
On very rare occasions, `Commit` might return `UNKNOWN`. This can happen, for example, if the client job experiences a 1+ hour networking failure. At that point, Cloud Spanner has lost track of the transaction outcome and we recommend that you perform another read from the database to see the state of things as they are now.
Sample code:
// This snippet has been automatically generated and should be regarded as a code template only. // It will require modifications to work: // - It may require correct/in-range values for request initialization. // - It may require specifying regional endpoints when creating the service client as shown in // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library try (SpannerClient spannerClient = SpannerClient.create()) { SessionName session = SessionName.of("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"); ByteString transactionId = ByteString.EMPTY; List<Mutation> mutations = new ArrayList<>(); CommitResponse response = spannerClient.commit(session, transactionId, mutations); }
- Parameters:
session
- Required. The session in which the transaction to be committed is running.transactionId
- Commit a previously-started transaction.mutations
- The mutations to be executed when this transaction commits. All mutations are applied atomically, in the order they appear in this list.- Throws:
com.google.api.gax.rpc.ApiException
- if the remote call fails
-
commit
public final CommitResponse commit(SessionName session, TransactionOptions singleUseTransaction, List<Mutation> mutations) Commits a transaction. The request includes the mutations to be applied to rows in the database.`Commit` might return an `ABORTED` error. This can occur at any time; commonly, the cause is conflicts with concurrent transactions. However, it can also happen for a variety of other reasons. If `Commit` returns `ABORTED`, the caller should re-attempt the transaction from the beginning, re-using the same session.
On very rare occasions, `Commit` might return `UNKNOWN`. This can happen, for example, if the client job experiences a 1+ hour networking failure. At that point, Cloud Spanner has lost track of the transaction outcome and we recommend that you perform another read from the database to see the state of things as they are now.
Sample code:
// This snippet has been automatically generated and should be regarded as a code template only. // It will require modifications to work: // - It may require correct/in-range values for request initialization. // - It may require specifying regional endpoints when creating the service client as shown in // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library try (SpannerClient spannerClient = SpannerClient.create()) { SessionName session = SessionName.of("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"); TransactionOptions singleUseTransaction = TransactionOptions.newBuilder().build(); List<Mutation> mutations = new ArrayList<>(); CommitResponse response = spannerClient.commit(session, singleUseTransaction, mutations); }
- Parameters:
session
- Required. The session in which the transaction to be committed is running.singleUseTransaction
- Execute mutations in a temporary transaction. Note that unlike commit of a previously-started transaction, commit with a temporary transaction is non-idempotent. That is, if the `CommitRequest` is sent to Cloud Spanner more than once (for instance, due to retries in the application, or in the transport library), it is possible that the mutations are executed more than once. If this is undesirable, use [BeginTransaction][google.spanner.v1.Spanner.BeginTransaction] and [Commit][google.spanner.v1.Spanner.Commit] instead.mutations
- The mutations to be executed when this transaction commits. All mutations are applied atomically, in the order they appear in this list.- Throws:
com.google.api.gax.rpc.ApiException
- if the remote call fails
-
commit
public final CommitResponse commit(String session, com.google.protobuf.ByteString transactionId, List<Mutation> mutations) Commits a transaction. The request includes the mutations to be applied to rows in the database.`Commit` might return an `ABORTED` error. This can occur at any time; commonly, the cause is conflicts with concurrent transactions. However, it can also happen for a variety of other reasons. If `Commit` returns `ABORTED`, the caller should re-attempt the transaction from the beginning, re-using the same session.
On very rare occasions, `Commit` might return `UNKNOWN`. This can happen, for example, if the client job experiences a 1+ hour networking failure. At that point, Cloud Spanner has lost track of the transaction outcome and we recommend that you perform another read from the database to see the state of things as they are now.
Sample code:
// This snippet has been automatically generated and should be regarded as a code template only. // It will require modifications to work: // - It may require correct/in-range values for request initialization. // - It may require specifying regional endpoints when creating the service client as shown in // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library try (SpannerClient spannerClient = SpannerClient.create()) { String session = SessionName.of("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]").toString(); ByteString transactionId = ByteString.EMPTY; List<Mutation> mutations = new ArrayList<>(); CommitResponse response = spannerClient.commit(session, transactionId, mutations); }
- Parameters:
session
- Required. The session in which the transaction to be committed is running.transactionId
- Commit a previously-started transaction.mutations
- The mutations to be executed when this transaction commits. All mutations are applied atomically, in the order they appear in this list.- Throws:
com.google.api.gax.rpc.ApiException
- if the remote call fails
-
commit
public final CommitResponse commit(String session, TransactionOptions singleUseTransaction, List<Mutation> mutations) Commits a transaction. The request includes the mutations to be applied to rows in the database.`Commit` might return an `ABORTED` error. This can occur at any time; commonly, the cause is conflicts with concurrent transactions. However, it can also happen for a variety of other reasons. If `Commit` returns `ABORTED`, the caller should re-attempt the transaction from the beginning, re-using the same session.
On very rare occasions, `Commit` might return `UNKNOWN`. This can happen, for example, if the client job experiences a 1+ hour networking failure. At that point, Cloud Spanner has lost track of the transaction outcome and we recommend that you perform another read from the database to see the state of things as they are now.
Sample code:
// This snippet has been automatically generated and should be regarded as a code template only. // It will require modifications to work: // - It may require correct/in-range values for request initialization. // - It may require specifying regional endpoints when creating the service client as shown in // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library try (SpannerClient spannerClient = SpannerClient.create()) { String session = SessionName.of("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]").toString(); TransactionOptions singleUseTransaction = TransactionOptions.newBuilder().build(); List<Mutation> mutations = new ArrayList<>(); CommitResponse response = spannerClient.commit(session, singleUseTransaction, mutations); }
- Parameters:
session
- Required. The session in which the transaction to be committed is running.singleUseTransaction
- Execute mutations in a temporary transaction. Note that unlike commit of a previously-started transaction, commit with a temporary transaction is non-idempotent. That is, if the `CommitRequest` is sent to Cloud Spanner more than once (for instance, due to retries in the application, or in the transport library), it is possible that the mutations are executed more than once. If this is undesirable, use [BeginTransaction][google.spanner.v1.Spanner.BeginTransaction] and [Commit][google.spanner.v1.Spanner.Commit] instead.mutations
- The mutations to be executed when this transaction commits. All mutations are applied atomically, in the order they appear in this list.- Throws:
com.google.api.gax.rpc.ApiException
- if the remote call fails
-
commit
Commits a transaction. The request includes the mutations to be applied to rows in the database.`Commit` might return an `ABORTED` error. This can occur at any time; commonly, the cause is conflicts with concurrent transactions. However, it can also happen for a variety of other reasons. If `Commit` returns `ABORTED`, the caller should re-attempt the transaction from the beginning, re-using the same session.
On very rare occasions, `Commit` might return `UNKNOWN`. This can happen, for example, if the client job experiences a 1+ hour networking failure. At that point, Cloud Spanner has lost track of the transaction outcome and we recommend that you perform another read from the database to see the state of things as they are now.
Sample code:
// This snippet has been automatically generated and should be regarded as a code template only. // It will require modifications to work: // - It may require correct/in-range values for request initialization. // - It may require specifying regional endpoints when creating the service client as shown in // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library try (SpannerClient spannerClient = SpannerClient.create()) { CommitRequest request = CommitRequest.newBuilder() .setSession( SessionName.of("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]").toString()) .addAllMutations(new ArrayList<Mutation>()) .setReturnCommitStats(true) .setRequestOptions(RequestOptions.newBuilder().build()) .build(); CommitResponse response = spannerClient.commit(request); }
- Parameters:
request
- The request object containing all of the parameters for the API call.- Throws:
com.google.api.gax.rpc.ApiException
- if the remote call fails
-
commitCallable
Commits a transaction. The request includes the mutations to be applied to rows in the database.`Commit` might return an `ABORTED` error. This can occur at any time; commonly, the cause is conflicts with concurrent transactions. However, it can also happen for a variety of other reasons. If `Commit` returns `ABORTED`, the caller should re-attempt the transaction from the beginning, re-using the same session.
On very rare occasions, `Commit` might return `UNKNOWN`. This can happen, for example, if the client job experiences a 1+ hour networking failure. At that point, Cloud Spanner has lost track of the transaction outcome and we recommend that you perform another read from the database to see the state of things as they are now.
Sample code:
// This snippet has been automatically generated and should be regarded as a code template only. // It will require modifications to work: // - It may require correct/in-range values for request initialization. // - It may require specifying regional endpoints when creating the service client as shown in // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library try (SpannerClient spannerClient = SpannerClient.create()) { CommitRequest request = CommitRequest.newBuilder() .setSession( SessionName.of("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]").toString()) .addAllMutations(new ArrayList<Mutation>()) .setReturnCommitStats(true) .setRequestOptions(RequestOptions.newBuilder().build()) .build(); ApiFuture<CommitResponse> future = spannerClient.commitCallable().futureCall(request); // Do something. CommitResponse response = future.get(); }
-
rollback
Rolls back a transaction, releasing any locks it holds. It is a good idea to call this for any transaction that includes one or more [Read][google.spanner.v1.Spanner.Read] or [ExecuteSql][google.spanner.v1.Spanner.ExecuteSql] requests and ultimately decides not to commit.`Rollback` returns `OK` if it successfully aborts the transaction, the transaction was already aborted, or the transaction is not found. `Rollback` never returns `ABORTED`.
Sample code:
// This snippet has been automatically generated and should be regarded as a code template only. // It will require modifications to work: // - It may require correct/in-range values for request initialization. // - It may require specifying regional endpoints when creating the service client as shown in // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library try (SpannerClient spannerClient = SpannerClient.create()) { SessionName session = SessionName.of("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"); ByteString transactionId = ByteString.EMPTY; spannerClient.rollback(session, transactionId); }
- Parameters:
session
- Required. The session in which the transaction to roll back is running.transactionId
- Required. The transaction to roll back.- Throws:
com.google.api.gax.rpc.ApiException
- if the remote call fails
-
rollback
Rolls back a transaction, releasing any locks it holds. It is a good idea to call this for any transaction that includes one or more [Read][google.spanner.v1.Spanner.Read] or [ExecuteSql][google.spanner.v1.Spanner.ExecuteSql] requests and ultimately decides not to commit.`Rollback` returns `OK` if it successfully aborts the transaction, the transaction was already aborted, or the transaction is not found. `Rollback` never returns `ABORTED`.
Sample code:
// This snippet has been automatically generated and should be regarded as a code template only. // It will require modifications to work: // - It may require correct/in-range values for request initialization. // - It may require specifying regional endpoints when creating the service client as shown in // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library try (SpannerClient spannerClient = SpannerClient.create()) { String session = SessionName.of("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]").toString(); ByteString transactionId = ByteString.EMPTY; spannerClient.rollback(session, transactionId); }
- Parameters:
session
- Required. The session in which the transaction to roll back is running.transactionId
- Required. The transaction to roll back.- Throws:
com.google.api.gax.rpc.ApiException
- if the remote call fails
-
rollback
Rolls back a transaction, releasing any locks it holds. It is a good idea to call this for any transaction that includes one or more [Read][google.spanner.v1.Spanner.Read] or [ExecuteSql][google.spanner.v1.Spanner.ExecuteSql] requests and ultimately decides not to commit.`Rollback` returns `OK` if it successfully aborts the transaction, the transaction was already aborted, or the transaction is not found. `Rollback` never returns `ABORTED`.
Sample code:
// This snippet has been automatically generated and should be regarded as a code template only. // It will require modifications to work: // - It may require correct/in-range values for request initialization. // - It may require specifying regional endpoints when creating the service client as shown in // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library try (SpannerClient spannerClient = SpannerClient.create()) { RollbackRequest request = RollbackRequest.newBuilder() .setSession( SessionName.of("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]").toString()) .setTransactionId(ByteString.EMPTY) .build(); spannerClient.rollback(request); }
- Parameters:
request
- The request object containing all of the parameters for the API call.- Throws:
com.google.api.gax.rpc.ApiException
- if the remote call fails
-
rollbackCallable
public final com.google.api.gax.rpc.UnaryCallable<RollbackRequest,com.google.protobuf.Empty> rollbackCallable()Rolls back a transaction, releasing any locks it holds. It is a good idea to call this for any transaction that includes one or more [Read][google.spanner.v1.Spanner.Read] or [ExecuteSql][google.spanner.v1.Spanner.ExecuteSql] requests and ultimately decides not to commit.`Rollback` returns `OK` if it successfully aborts the transaction, the transaction was already aborted, or the transaction is not found. `Rollback` never returns `ABORTED`.
Sample code:
// This snippet has been automatically generated and should be regarded as a code template only. // It will require modifications to work: // - It may require correct/in-range values for request initialization. // - It may require specifying regional endpoints when creating the service client as shown in // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library try (SpannerClient spannerClient = SpannerClient.create()) { RollbackRequest request = RollbackRequest.newBuilder() .setSession( SessionName.of("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]").toString()) .setTransactionId(ByteString.EMPTY) .build(); ApiFuture<Empty> future = spannerClient.rollbackCallable().futureCall(request); // Do something. future.get(); }
-
partitionQuery
Creates a set of partition tokens that can be used to execute a query operation in parallel. Each of the returned partition tokens can be used by [ExecuteStreamingSql][google.spanner.v1.Spanner.ExecuteStreamingSql] to specify a subset of the query result to read. The same session and read-only transaction must be used by the PartitionQueryRequest used to create the partition tokens and the ExecuteSqlRequests that use the partition tokens.Partition tokens become invalid when the session used to create them is deleted, is idle for too long, begins a new transaction, or becomes too old. When any of these happen, it is not possible to resume the query, and the whole operation must be restarted from the beginning.
Sample code:
// This snippet has been automatically generated and should be regarded as a code template only. // It will require modifications to work: // - It may require correct/in-range values for request initialization. // - It may require specifying regional endpoints when creating the service client as shown in // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library try (SpannerClient spannerClient = SpannerClient.create()) { PartitionQueryRequest request = PartitionQueryRequest.newBuilder() .setSession( SessionName.of("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]").toString()) .setTransaction(TransactionSelector.newBuilder().build()) .setSql("sql114126") .setParams(Struct.newBuilder().build()) .putAllParamTypes(new HashMap<String, Type>()) .setPartitionOptions(PartitionOptions.newBuilder().build()) .build(); PartitionResponse response = spannerClient.partitionQuery(request); }
- Parameters:
request
- The request object containing all of the parameters for the API call.- Throws:
com.google.api.gax.rpc.ApiException
- if the remote call fails
-
partitionQueryCallable
public final com.google.api.gax.rpc.UnaryCallable<PartitionQueryRequest,PartitionResponse> partitionQueryCallable()Creates a set of partition tokens that can be used to execute a query operation in parallel. Each of the returned partition tokens can be used by [ExecuteStreamingSql][google.spanner.v1.Spanner.ExecuteStreamingSql] to specify a subset of the query result to read. The same session and read-only transaction must be used by the PartitionQueryRequest used to create the partition tokens and the ExecuteSqlRequests that use the partition tokens.Partition tokens become invalid when the session used to create them is deleted, is idle for too long, begins a new transaction, or becomes too old. When any of these happen, it is not possible to resume the query, and the whole operation must be restarted from the beginning.
Sample code:
// This snippet has been automatically generated and should be regarded as a code template only. // It will require modifications to work: // - It may require correct/in-range values for request initialization. // - It may require specifying regional endpoints when creating the service client as shown in // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library try (SpannerClient spannerClient = SpannerClient.create()) { PartitionQueryRequest request = PartitionQueryRequest.newBuilder() .setSession( SessionName.of("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]").toString()) .setTransaction(TransactionSelector.newBuilder().build()) .setSql("sql114126") .setParams(Struct.newBuilder().build()) .putAllParamTypes(new HashMap<String, Type>()) .setPartitionOptions(PartitionOptions.newBuilder().build()) .build(); ApiFuture<PartitionResponse> future = spannerClient.partitionQueryCallable().futureCall(request); // Do something. PartitionResponse response = future.get(); }
-
partitionRead
Creates a set of partition tokens that can be used to execute a read operation in parallel. Each of the returned partition tokens can be used by [StreamingRead][google.spanner.v1.Spanner.StreamingRead] to specify a subset of the read result to read. The same session and read-only transaction must be used by the PartitionReadRequest used to create the partition tokens and the ReadRequests that use the partition tokens. There are no ordering guarantees on rows returned among the returned partition tokens, or even within each individual StreamingRead call issued with a partition_token.Partition tokens become invalid when the session used to create them is deleted, is idle for too long, begins a new transaction, or becomes too old. When any of these happen, it is not possible to resume the read, and the whole operation must be restarted from the beginning.
Sample code:
// This snippet has been automatically generated and should be regarded as a code template only. // It will require modifications to work: // - It may require correct/in-range values for request initialization. // - It may require specifying regional endpoints when creating the service client as shown in // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library try (SpannerClient spannerClient = SpannerClient.create()) { PartitionReadRequest request = PartitionReadRequest.newBuilder() .setSession( SessionName.of("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]").toString()) .setTransaction(TransactionSelector.newBuilder().build()) .setTable("table110115790") .setIndex("index100346066") .addAllColumns(new ArrayList<String>()) .setKeySet(KeySet.newBuilder().build()) .setPartitionOptions(PartitionOptions.newBuilder().build()) .build(); PartitionResponse response = spannerClient.partitionRead(request); }
- Parameters:
request
- The request object containing all of the parameters for the API call.- Throws:
com.google.api.gax.rpc.ApiException
- if the remote call fails
-
partitionReadCallable
public final com.google.api.gax.rpc.UnaryCallable<PartitionReadRequest,PartitionResponse> partitionReadCallable()Creates a set of partition tokens that can be used to execute a read operation in parallel. Each of the returned partition tokens can be used by [StreamingRead][google.spanner.v1.Spanner.StreamingRead] to specify a subset of the read result to read. The same session and read-only transaction must be used by the PartitionReadRequest used to create the partition tokens and the ReadRequests that use the partition tokens. There are no ordering guarantees on rows returned among the returned partition tokens, or even within each individual StreamingRead call issued with a partition_token.Partition tokens become invalid when the session used to create them is deleted, is idle for too long, begins a new transaction, or becomes too old. When any of these happen, it is not possible to resume the read, and the whole operation must be restarted from the beginning.
Sample code:
// This snippet has been automatically generated and should be regarded as a code template only. // It will require modifications to work: // - It may require correct/in-range values for request initialization. // - It may require specifying regional endpoints when creating the service client as shown in // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library try (SpannerClient spannerClient = SpannerClient.create()) { PartitionReadRequest request = PartitionReadRequest.newBuilder() .setSession( SessionName.of("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]").toString()) .setTransaction(TransactionSelector.newBuilder().build()) .setTable("table110115790") .setIndex("index100346066") .addAllColumns(new ArrayList<String>()) .setKeySet(KeySet.newBuilder().build()) .setPartitionOptions(PartitionOptions.newBuilder().build()) .build(); ApiFuture<PartitionResponse> future = spannerClient.partitionReadCallable().futureCall(request); // Do something. PartitionResponse response = future.get(); }
-
batchWriteCallable
public final com.google.api.gax.rpc.ServerStreamingCallable<BatchWriteRequest,BatchWriteResponse> batchWriteCallable()Batches the supplied mutation groups in a collection of efficient transactions. All mutations in a group are committed atomically. However, mutations across groups can be committed non-atomically in an unspecified order and thus, they must be independent of each other. Partial failure is possible, i.e., some groups may have been committed successfully, while some may have failed. The results of individual batches are streamed into the response as the batches are applied.BatchWrite requests are not replay protected, meaning that each mutation group may be applied more than once. Replays of non-idempotent mutations may have undesirable effects. For example, replays of an insert mutation may produce an already exists error or if you use generated or commit timestamp-based keys, it may result in additional rows being added to the mutation's table. We recommend structuring your mutation groups to be idempotent to avoid this issue.
Sample code:
// This snippet has been automatically generated and should be regarded as a code template only. // It will require modifications to work: // - It may require correct/in-range values for request initialization. // - It may require specifying regional endpoints when creating the service client as shown in // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library try (SpannerClient spannerClient = SpannerClient.create()) { BatchWriteRequest request = BatchWriteRequest.newBuilder() .setSession( SessionName.of("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]").toString()) .setRequestOptions(RequestOptions.newBuilder().build()) .addAllMutationGroups(new ArrayList<BatchWriteRequest.MutationGroup>()) .build(); ServerStream<BatchWriteResponse> stream = spannerClient.batchWriteCallable().call(request); for (BatchWriteResponse response : stream) { // Do something when a response is received. } }
-
close
public final void close()- Specified by:
close
in interfaceAutoCloseable
-
shutdown
public void shutdown()- Specified by:
shutdown
in interfacecom.google.api.gax.core.BackgroundResource
-
isShutdown
public boolean isShutdown()- Specified by:
isShutdown
in interfacecom.google.api.gax.core.BackgroundResource
-
isTerminated
public boolean isTerminated()- Specified by:
isTerminated
in interfacecom.google.api.gax.core.BackgroundResource
-
shutdownNow
public void shutdownNow()- Specified by:
shutdownNow
in interfacecom.google.api.gax.core.BackgroundResource
-
awaitTermination
- Specified by:
awaitTermination
in interfacecom.google.api.gax.core.BackgroundResource
- Throws:
InterruptedException
-