public T executeReadOnlyTransactionWithStaleness()

in google-cloud-spanner-hibernate-samples/spring-data-jpa-full-sample/src/main/java/com/google/cloud/spanner/sample/service/StaleReadService.java [65:87]


  public <T> T executeReadOnlyTransactionWithStaleness(String staleness, Supplier<T> transaction) {
    return entityManager
        .unwrap(Session.class)
        .doReturningWork(
            connection -> {
              try (Statement statement = connection.createStatement()) {
                try {
                  statement.execute(String.format("set read_only_staleness='%s'", staleness));
                  return transaction.get();
                } catch (Throwable t) {
                  statement.execute("rollback");
                  throw t;
                } finally {
                  // NOTE: Calling 'commit' if there is no active transaction is a no-op. That means
                  // that if the transaction was rolled back in case of an exception, this commit
                  // will be a no-op.
                  statement.execute("commit");
                  // Reset the read_only_staleness of the connection.
                  connection.createStatement().execute("set read_only_staleness='strong'");
                }
              }
            });
  }