Amazon QLDB driver for Java – Quick start tutorial - Amazon Quantum Ledger Database (Amazon QLDB)

Amazon QLDB driver for Java – Quick start tutorial

In this tutorial, you learn how to set up a simple application using the latest version of the Amazon QLDB driver for Java. This guide includes steps for installing the driver and short code examples of basic create, read, update, and delete (CRUD) operations. For more in-depth examples that demonstrate these operations in a full sample application, see the Java tutorial.

Prerequisites

Before you get started, make sure that you do the following:

  1. Complete the Prerequisites for the Java driver, if you haven't already done so. This includes signing up for AWS, getting an AWS access key for development, and installing a Java integrated development environment (IDE).

  2. Create a ledger named quick-start.

    To learn how to create a ledger, see Basic operations for Amazon QLDB ledgers or Step 1: Create a new ledger in Getting started with the console.

Step 1: Set up your project

First, set up your Java project. We recommend using the Maven dependency management system for this tutorial.

Note

If you use an IDE that has features to automate these setup steps, you can skip ahead to Step 2: Initialize the driver.

  1. Create a folder for your application.

    $ mkdir myproject $ cd myproject
  2. Enter the following command to initialize your project from a Maven template. Replace project-package, project-name, and maven-template with your own values as appropriate.

    $ mvn archetype:generate -DgroupId=project-package \ -DartifactId=project-name \ -DarchetypeArtifactId=maven-template \ -DinteractiveMode=false

    For maven-template, you can use the basic Maven template: maven-archetype-quickstart

  3. To add the QLDB driver for Java as a project dependency, navigate to your newly created pom.xml file and add the following artifact.

    <dependency> <groupId>software.amazon.qldb</groupId> <artifactId>amazon-qldb-driver-java</artifactId> <version>2.3.1</version> </dependency>

    This artifact automatically includes the AWS SDK for Java 2.x core module, Amazon Ion libraries, and other required dependencies. Your pom.xml file should now look similar to the following.

    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>software.amazon.qldb</groupId> <artifactId>qldb-quickstart</artifactId> <packaging>jar</packaging> <version>1.0-SNAPSHOT</version> <name>qldb-quickstart</name> <url>http://maven.apache.org</url> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <dependency> <groupId>software.amazon.qldb</groupId> <artifactId>amazon-qldb-driver-java</artifactId> <version>2.3.1</version> </dependency> </dependencies> </project>
  4. Open the App.java file.

    Then, incrementally add the code examples in the following steps to try some basic CRUD operations. Or, you can skip the step-by-step tutorial and instead run the complete application.

Step 2: Initialize the driver

Initialize an instance of the driver that connects to the ledger named quick-start. Add the following code to your App.java file.

import java.util.*; import com.amazon.ion.*; import com.amazon.ion.system.*; import software.amazon.awssdk.services.qldbsession.QldbSessionClient; import software.amazon.qldb.*; public final class App { public static IonSystem ionSys = IonSystemBuilder.standard().build(); public static QldbDriver qldbDriver; public static void main(final String... args) { System.out.println("Initializing the driver"); qldbDriver = QldbDriver.builder() .ledger("quick-start") .transactionRetryPolicy(RetryPolicy .builder() .maxRetries(3) .build()) .sessionClientBuilder(QldbSessionClient.builder()) .build(); } }

Step 3: Create a table and an index

The following code example shows how to run CREATE TABLE and CREATE INDEX statements.

In the main method, add the following code that creates a table named People and an index for the lastName field on that table. Indexes are required to optimize query performance and help to limit optimistic concurrency control (OCC) conflict exceptions.

// Create a table and an index in the same transaction qldbDriver.execute(txn -> { System.out.println("Creating a table and an index"); txn.execute("CREATE TABLE People"); txn.execute("CREATE INDEX ON People(lastName)"); });

Step 4: Insert a document

The following code example shows how to run an INSERT statement. QLDB supports the PartiQL query language (SQL compatible) and the Amazon Ion data format (superset of JSON).

Add the following code that inserts a document into the People table.

// Insert a document qldbDriver.execute(txn -> { System.out.println("Inserting a document"); IonStruct person = ionSys.newEmptyStruct(); person.put("firstName").newString("John"); person.put("lastName").newString("Doe"); person.put("age").newInt(32); txn.execute("INSERT INTO People ?", person); });

This example uses a question mark (?) as a variable placeholder to pass the document information to the statement. When you use placeholders, you must pass a value of type IonValue.

Tip

To insert multiple documents by using a single INSERT statement, you can pass a parameter of type IonList (explicitly cast as an IonValue) to the statement as follows.

// people is an IonList explicitly cast as an IonValue txn.execute("INSERT INTO People ?", (IonValue) people);

You don't enclose the variable placeholder (?) in double angle brackets ( <<...>> ) when passing an IonList. In manual PartiQL statements, double angle brackets denote an unordered collection known as a bag.

Step 5: Query the document

The following code example shows how to run a SELECT statement.

Add the following code that queries a document from the People table.

// Query the document qldbDriver.execute(txn -> { System.out.println("Querying the table"); Result result = txn.execute("SELECT * FROM People WHERE lastName = ?", ionSys.newString("Doe")); IonStruct person = (IonStruct) result.iterator().next(); System.out.println(person.get("firstName")); // prints John System.out.println(person.get("lastName")); // prints Doe System.out.println(person.get("age")); // prints 32 });

Step 6: Update the document

The following code example shows how to run an UPDATE statement.

  1. Add the following code that updates a document in the People table by updating age to 42.

    // Update the document qldbDriver.execute(txn -> { System.out.println("Updating the document"); final List<IonValue> parameters = new ArrayList<>(); parameters.add(ionSys.newInt(42)); parameters.add(ionSys.newString("Doe")); txn.execute("UPDATE People SET age = ? WHERE lastName = ?", parameters); });
  2. Query the document again to see the updated value.

    // Query the updated document qldbDriver.execute(txn -> { System.out.println("Querying the table for the updated document"); Result result = txn.execute("SELECT * FROM People WHERE lastName = ?", ionSys.newString("Doe")); IonStruct person = (IonStruct) result.iterator().next(); System.out.println(person.get("firstName")); // prints John System.out.println(person.get("lastName")); // prints Doe System.out.println(person.get("age")); // prints 32 });
  3. Use Maven or your IDE to compile and run the App.java file.

Running the complete application

The following code example is the complete version of the App.java application. Instead of doing the previous steps individually, you can also copy and run this code example end to end. This application demonstrates some basic CRUD operations on the ledger named quick-start.

Note

Before you run this code, make sure that you don't already have an active table named People in the quick-start ledger.

On the first line, replace project-package with the groupId value that you used for the Maven command in Step 1: Set up your project.

package project-package; import java.util.*; import com.amazon.ion.*; import com.amazon.ion.system.*; import software.amazon.awssdk.services.qldbsession.QldbSessionClient; import software.amazon.qldb.*; public class App { public static IonSystem ionSys = IonSystemBuilder.standard().build(); public static QldbDriver qldbDriver; public static void main(final String... args) { System.out.println("Initializing the driver"); qldbDriver = QldbDriver.builder() .ledger("quick-start") .transactionRetryPolicy(RetryPolicy .builder() .maxRetries(3) .build()) .sessionClientBuilder(QldbSessionClient.builder()) .build(); // Create a table and an index in the same transaction qldbDriver.execute(txn -> { System.out.println("Creating a table and an index"); txn.execute("CREATE TABLE People"); txn.execute("CREATE INDEX ON People(lastName)"); }); // Insert a document qldbDriver.execute(txn -> { System.out.println("Inserting a document"); IonStruct person = ionSys.newEmptyStruct(); person.put("firstName").newString("John"); person.put("lastName").newString("Doe"); person.put("age").newInt(32); txn.execute("INSERT INTO People ?", person); }); // Query the document qldbDriver.execute(txn -> { System.out.println("Querying the table"); Result result = txn.execute("SELECT * FROM People WHERE lastName = ?", ionSys.newString("Doe")); IonStruct person = (IonStruct) result.iterator().next(); System.out.println(person.get("firstName")); // prints John System.out.println(person.get("lastName")); // prints Doe System.out.println(person.get("age")); // prints 32 }); // Update the document qldbDriver.execute(txn -> { System.out.println("Updating the document"); final List<IonValue> parameters = new ArrayList<>(); parameters.add(ionSys.newInt(42)); parameters.add(ionSys.newString("Doe")); txn.execute("UPDATE People SET age = ? WHERE lastName = ?", parameters); }); // Query the updated document qldbDriver.execute(txn -> { System.out.println("Querying the table for the updated document"); Result result = txn.execute("SELECT * FROM People WHERE lastName = ?", ionSys.newString("Doe")); IonStruct person = (IonStruct) result.iterator().next(); System.out.println(person.get("firstName")); // prints John System.out.println(person.get("lastName")); // prints Doe System.out.println(person.get("age")); // prints 42 }); } }

Use Maven or your IDE to compile and run the App.java file.