Step 3: Create tables, indexes, and sample data - Amazon Quantum Ledger Database (Amazon QLDB)

Step 3: Create tables, indexes, and sample data

When your Amazon QLDB ledger is active and accepts connections, you can start creating tables for data about vehicles, their owners, and their registration information. After creating the tables and indexes, you can load them with data.

In this step, you create four tables in the vehicle-registration ledger:

  • VehicleRegistration

  • Vehicle

  • Person

  • DriversLicense

You also create the following indexes.

Table name Field
VehicleRegistration VIN
VehicleRegistration LicensePlateNumber
Vehicle VIN
Person GovId
DriversLicense LicenseNumber
DriversLicense PersonId

When inserting sample data, you first insert documents into the Person table. Then, you use the system-assigned id from each Person document to populate the corresponding fields in the appropriate VehicleRegistration and DriversLicense documents.

Tip

As a best practice, use a document's system-assigned id as a foreign key. While you can define fields that are intended to be unique identifiers (for example, a vehicle's VIN), the true unique identifier of a document is its id. This field is included in the document's metadata, which you can query in the committed view (the system-defined view of a table).

For more information about views in QLDB, see Core concepts. To learn more about metadata, see Querying document metadata.

To set up the sample data

  1. Review the following .java files. These model classes represent documents that you store in the vehicle-registration tables. They're serializable to and from Amazon Ion format.

    Note

    QLDB documents are stored in Ion format. So, you can use FasterXML's Jackson library to model the data in JSON.

    2.x
    1. DriversLicense.java

      /* * Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: MIT-0 * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * software and associated documentation files (the "Software"), to deal in the Software * without restriction, including without limitation the rights to use, copy, modify, * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package software.amazon.qldb.tutorial.model; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import software.amazon.qldb.tutorial.model.streams.RevisionData; import java.time.LocalDate; /** * Represents a driver's license, serializable to (and from) Ion. */ public final class DriversLicense implements RevisionData { private final String personId; private final String licenseNumber; private final String licenseType; @JsonSerialize(using = IonLocalDateSerializer.class) @JsonDeserialize(using = IonLocalDateDeserializer.class) private final LocalDate validFromDate; @JsonSerialize(using = IonLocalDateSerializer.class) @JsonDeserialize(using = IonLocalDateDeserializer.class) private final LocalDate validToDate; @JsonCreator public DriversLicense(@JsonProperty("PersonId") final String personId, @JsonProperty("LicenseNumber") final String licenseNumber, @JsonProperty("LicenseType") final String licenseType, @JsonProperty("ValidFromDate") final LocalDate validFromDate, @JsonProperty("ValidToDate") final LocalDate validToDate) { this.personId = personId; this.licenseNumber = licenseNumber; this.licenseType = licenseType; this.validFromDate = validFromDate; this.validToDate = validToDate; } @JsonProperty("PersonId") public String getPersonId() { return personId; } @JsonProperty("LicenseNumber") public String getLicenseNumber() { return licenseNumber; } @JsonProperty("LicenseType") public String getLicenseType() { return licenseType; } @JsonProperty("ValidFromDate") public LocalDate getValidFromDate() { return validFromDate; } @JsonProperty("ValidToDate") public LocalDate getValidToDate() { return validToDate; } @Override public String toString() { return "DriversLicense{" + "personId='" + personId + '\'' + ", licenseNumber='" + licenseNumber + '\'' + ", licenseType='" + licenseType + '\'' + ", validFromDate=" + validFromDate + ", validToDate=" + validToDate + '}'; } }
    2. Person.java

      /* * Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: MIT-0 * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * software and associated documentation files (the "Software"), to deal in the Software * without restriction, including without limitation the rights to use, copy, modify, * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package software.amazon.qldb.tutorial.model; import java.time.LocalDate; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import software.amazon.qldb.TransactionExecutor; import software.amazon.qldb.tutorial.Constants; import software.amazon.qldb.tutorial.model.streams.RevisionData; /** * Represents a person, serializable to (and from) Ion. */ public final class Person implements RevisionData { private final String firstName; private final String lastName; @JsonSerialize(using = IonLocalDateSerializer.class) @JsonDeserialize(using = IonLocalDateDeserializer.class) private final LocalDate dob; private final String govId; private final String govIdType; private final String address; @JsonCreator public Person(@JsonProperty("FirstName") final String firstName, @JsonProperty("LastName") final String lastName, @JsonProperty("DOB") final LocalDate dob, @JsonProperty("GovId") final String govId, @JsonProperty("GovIdType") final String govIdType, @JsonProperty("Address") final String address) { this.firstName = firstName; this.lastName = lastName; this.dob = dob; this.govId = govId; this.govIdType = govIdType; this.address = address; } @JsonProperty("Address") public String getAddress() { return address; } @JsonProperty("DOB") public LocalDate getDob() { return dob; } @JsonProperty("FirstName") public String getFirstName() { return firstName; } @JsonProperty("LastName") public String getLastName() { return lastName; } @JsonProperty("GovId") public String getGovId() { return govId; } @JsonProperty("GovIdType") public String getGovIdType() { return govIdType; } /** * This returns the unique document ID given a specific government ID. * * @param txn * A transaction executor object. * @param govId * The government ID of a driver. * @return the unique document ID. */ public static String getDocumentIdByGovId(final TransactionExecutor txn, final String govId) { return SampleData.getDocumentId(txn, Constants.PERSON_TABLE_NAME, "GovId", govId); } @Override public String toString() { return "Person{" + "firstName='" + firstName + '\'' + ", lastName='" + lastName + '\'' + ", dob=" + dob + ", govId='" + govId + '\'' + ", govIdType='" + govIdType + '\'' + ", address='" + address + '\'' + '}'; } }
    3. VehicleRegistration.java

      /* * Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: MIT-0 * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * software and associated documentation files (the "Software"), to deal in the Software * without restriction, including without limitation the rights to use, copy, modify, * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package software.amazon.qldb.tutorial.model; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import software.amazon.qldb.TransactionExecutor; import software.amazon.qldb.tutorial.Constants; import software.amazon.qldb.tutorial.model.streams.RevisionData; import java.math.BigDecimal; import java.time.LocalDate; /** * Represents a vehicle registration, serializable to (and from) Ion. */ public final class VehicleRegistration implements RevisionData { private final String vin; private final String licensePlateNumber; private final String state; private final String city; private final BigDecimal pendingPenaltyTicketAmount; private final LocalDate validFromDate; private final LocalDate validToDate; private final Owners owners; @JsonCreator public VehicleRegistration(@JsonProperty("VIN") final String vin, @JsonProperty("LicensePlateNumber") final String licensePlateNumber, @JsonProperty("State") final String state, @JsonProperty("City") final String city, @JsonProperty("PendingPenaltyTicketAmount") final BigDecimal pendingPenaltyTicketAmount, @JsonProperty("ValidFromDate") final LocalDate validFromDate, @JsonProperty("ValidToDate") final LocalDate validToDate, @JsonProperty("Owners") final Owners owners) { this.vin = vin; this.licensePlateNumber = licensePlateNumber; this.state = state; this.city = city; this.pendingPenaltyTicketAmount = pendingPenaltyTicketAmount; this.validFromDate = validFromDate; this.validToDate = validToDate; this.owners = owners; } @JsonProperty("City") public String getCity() { return city; } @JsonProperty("LicensePlateNumber") public String getLicensePlateNumber() { return licensePlateNumber; } @JsonProperty("Owners") public Owners getOwners() { return owners; } @JsonProperty("PendingPenaltyTicketAmount") public BigDecimal getPendingPenaltyTicketAmount() { return pendingPenaltyTicketAmount; } @JsonProperty("State") public String getState() { return state; } @JsonProperty("ValidFromDate") @JsonSerialize(using = IonLocalDateSerializer.class) @JsonDeserialize(using = IonLocalDateDeserializer.class) public LocalDate getValidFromDate() { return validFromDate; } @JsonProperty("ValidToDate") @JsonSerialize(using = IonLocalDateSerializer.class) @JsonDeserialize(using = IonLocalDateDeserializer.class) public LocalDate getValidToDate() { return validToDate; } @JsonProperty("VIN") public String getVin() { return vin; } /** * Returns the unique document ID of a vehicle given a specific VIN. * * @param txn * A transaction executor object. * @param vin * The VIN of a vehicle. * @return the unique document ID of the specified vehicle. */ public static String getDocumentIdByVin(final TransactionExecutor txn, final String vin) { return SampleData.getDocumentId(txn, Constants.VEHICLE_REGISTRATION_TABLE_NAME, "VIN", vin); } @Override public String toString() { return "VehicleRegistration{" + "vin='" + vin + '\'' + ", licensePlateNumber='" + licensePlateNumber + '\'' + ", state='" + state + '\'' + ", city='" + city + '\'' + ", pendingPenaltyTicketAmount=" + pendingPenaltyTicketAmount + ", validFromDate=" + validFromDate + ", validToDate=" + validToDate + ", owners=" + owners + '}'; } }
    4. Vehicle.java

      /* * Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: MIT-0 * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * software and associated documentation files (the "Software"), to deal in the Software * without restriction, including without limitation the rights to use, copy, modify, * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package software.amazon.qldb.tutorial.model; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import software.amazon.qldb.tutorial.model.streams.RevisionData; /** * Represents a vehicle, serializable to (and from) Ion. */ public final class Vehicle implements RevisionData { private final String vin; private final String type; private final int year; private final String make; private final String model; private final String color; @JsonCreator public Vehicle(@JsonProperty("VIN") final String vin, @JsonProperty("Type") final String type, @JsonProperty("Year") final int year, @JsonProperty("Make") final String make, @JsonProperty("Model") final String model, @JsonProperty("Color") final String color) { this.vin = vin; this.type = type; this.year = year; this.make = make; this.model = model; this.color = color; } @JsonProperty("Color") public String getColor() { return color; } @JsonProperty("Make") public String getMake() { return make; } @JsonProperty("Model") public String getModel() { return model; } @JsonProperty("Type") public String getType() { return type; } @JsonProperty("VIN") public String getVin() { return vin; } @JsonProperty("Year") public int getYear() { return year; } @Override public String toString() { return "Vehicle{" + "vin='" + vin + '\'' + ", type='" + type + '\'' + ", year=" + year + ", make='" + make + '\'' + ", model='" + model + '\'' + ", color='" + color + '\'' + '}'; } }
    5. Owner.java

      /* * Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: MIT-0 * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * software and associated documentation files (the "Software"), to deal in the Software * without restriction, including without limitation the rights to use, copy, modify, * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package software.amazon.qldb.tutorial.model; import com.fasterxml.jackson.annotation.JsonProperty; /** * Represents a vehicle owner, serializable to (and from) Ion. */ public final class Owner { private final String personId; public Owner(@JsonProperty("PersonId") final String personId) { this.personId = personId; } @JsonProperty("PersonId") public String getPersonId() { return personId; } @Override public String toString() { return "Owner{" + "personId='" + personId + '\'' + '}'; } }
    6. Owners.java

      /* * Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: MIT-0 * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * software and associated documentation files (the "Software"), to deal in the Software * without restriction, including without limitation the rights to use, copy, modify, * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package software.amazon.qldb.tutorial.model; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.List; /** * Represents a set of owners for a given vehicle, serializable to (and from) Ion. */ public final class Owners { private final Owner primaryOwner; private final List<Owner> secondaryOwners; public Owners(@JsonProperty("PrimaryOwner") final Owner primaryOwner, @JsonProperty("SecondaryOwners") final List<Owner> secondaryOwners) { this.primaryOwner = primaryOwner; this.secondaryOwners = secondaryOwners; } @JsonProperty("PrimaryOwner") public Owner getPrimaryOwner() { return primaryOwner; } @JsonProperty("SecondaryOwners") public List<Owner> getSecondaryOwners() { return secondaryOwners; } @Override public String toString() { return "Owners{" + "primaryOwner=" + primaryOwner + ", secondaryOwners=" + secondaryOwners + '}'; } }
    7. DmlResultDocument.java

      /* * Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: MIT-0 * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * software and associated documentation files (the "Software"), to deal in the Software * without restriction, including without limitation the rights to use, copy, modify, * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package software.amazon.qldb.tutorial.qldb; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; /** * Contains information about an individual document inserted or modified * as a result of DML. */ public class DmlResultDocument { private String documentId; @JsonCreator public DmlResultDocument(@JsonProperty("documentId") final String documentId) { this.documentId = documentId; } public String getDocumentId() { return documentId; } @Override public String toString() { return "DmlResultDocument{" + "documentId='" + documentId + '\'' + '}'; } }
    8. IonLocalDateDeserializer.java

      /* * Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: MIT-0 * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * software and associated documentation files (the "Software"), to deal in the Software * without restriction, including without limitation the rights to use, copy, modify, * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package software.amazon.qldb.tutorial.model; import com.amazon.ion.Timestamp; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.JsonDeserializer; import java.io.IOException; import java.time.LocalDate; /** * Deserializes [java.time.LocalDate] from Ion. */ public class IonLocalDateDeserializer extends JsonDeserializer<LocalDate> { @Override public LocalDate deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException { return timestampToLocalDate((Timestamp) jp.getEmbeddedObject()); } private LocalDate timestampToLocalDate(Timestamp timestamp) { return LocalDate.of(timestamp.getYear(), timestamp.getMonth(), timestamp.getDay()); } }
    9. IonLocalDateSerializer.java

      /* * Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: MIT-0 * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * software and associated documentation files (the "Software"), to deal in the Software * without restriction, including without limitation the rights to use, copy, modify, * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package software.amazon.qldb.tutorial.model; import com.amazon.ion.Timestamp; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.SerializerProvider; import com.fasterxml.jackson.databind.ser.std.StdScalarSerializer; import com.fasterxml.jackson.dataformat.ion.IonGenerator; import java.io.IOException; import java.time.LocalDate; /** * Serializes [java.time.LocalDate] to Ion. */ public class IonLocalDateSerializer extends StdScalarSerializer<LocalDate> { public IonLocalDateSerializer() { super(LocalDate.class); } @Override public void serialize(LocalDate date, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException { Timestamp timestamp = Timestamp.forDay(date.getYear(), date.getMonthValue(), date.getDayOfMonth()); ((IonGenerator) jsonGenerator).writeValue(timestamp); } }
    10. RevisionData.java

      /* * Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: MIT-0 * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * software and associated documentation files (the "Software"), to deal in the Software * without restriction, including without limitation the rights to use, copy, modify, * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package software.amazon.qldb.tutorial.model.streams; /** * Allows modeling the content of all revisions as a generic revision data. Used * in the {@link Revision} and extended by domain models in {@link * software.amazon.qldb.tutorial.model} to make it easier to write the {@link * Revision.RevisionDataDeserializer} that must deserialize the {@link * Revision#data} from different domain models. */ public interface RevisionData { }
    1.x
    1. DriversLicense.java

      /* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: MIT-0 * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * software and associated documentation files (the "Software"), to deal in the Software * without restriction, including without limitation the rights to use, copy, modify, * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package software.amazon.qldb.tutorial.model; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import software.amazon.qldb.tutorial.model.streams.RevisionData; import java.time.LocalDate; /** * Represents a driver's license, serializable to (and from) Ion. */ public final class DriversLicense implements RevisionData { private final String personId; private final String licenseNumber; private final String licenseType; @JsonSerialize(using = IonLocalDateSerializer.class) @JsonDeserialize(using = IonLocalDateDeserializer.class) private final LocalDate validFromDate; @JsonSerialize(using = IonLocalDateSerializer.class) @JsonDeserialize(using = IonLocalDateDeserializer.class) private final LocalDate validToDate; @JsonCreator public DriversLicense(@JsonProperty("PersonId") final String personId, @JsonProperty("LicenseNumber") final String licenseNumber, @JsonProperty("LicenseType") final String licenseType, @JsonProperty("ValidFromDate") final LocalDate validFromDate, @JsonProperty("ValidToDate") final LocalDate validToDate) { this.personId = personId; this.licenseNumber = licenseNumber; this.licenseType = licenseType; this.validFromDate = validFromDate; this.validToDate = validToDate; } @JsonProperty("PersonId") public String getPersonId() { return personId; } @JsonProperty("LicenseNumber") public String getLicenseNumber() { return licenseNumber; } @JsonProperty("LicenseType") public String getLicenseType() { return licenseType; } @JsonProperty("ValidFromDate") public LocalDate getValidFromDate() { return validFromDate; } @JsonProperty("ValidToDate") public LocalDate getValidToDate() { return validToDate; } @Override public String toString() { return "DriversLicense{" + "personId='" + personId + '\'' + ", licenseNumber='" + licenseNumber + '\'' + ", licenseType='" + licenseType + '\'' + ", validFromDate=" + validFromDate + ", validToDate=" + validToDate + '}'; } }
    2. Person.java

      /* * Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: MIT-0 * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * software and associated documentation files (the "Software"), to deal in the Software * without restriction, including without limitation the rights to use, copy, modify, * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package software.amazon.qldb.tutorial.model; import java.time.LocalDate; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import software.amazon.qldb.TransactionExecutor; import software.amazon.qldb.tutorial.Constants; import software.amazon.qldb.tutorial.model.streams.RevisionData; import java.time.LocalDate; /** * Represents a person, serializable to (and from) Ion. */ public final class Person implements RevisionData { private final String firstName; private final String lastName; @JsonSerialize(using = IonLocalDateSerializer.class) @JsonDeserialize(using = IonLocalDateDeserializer.class) private final LocalDate dob; private final String govId; private final String govIdType; private final String address; @JsonCreator public Person(@JsonProperty("FirstName") final String firstName, @JsonProperty("LastName") final String lastName, @JsonProperty("DOB") final LocalDate dob, @JsonProperty("GovId") final String govId, @JsonProperty("GovIdType") final String govIdType, @JsonProperty("Address") final String address) { this.firstName = firstName; this.lastName = lastName; this.dob = dob; this.govId = govId; this.govIdType = govIdType; this.address = address; } @JsonProperty("Address") public String getAddress() { return address; } @JsonProperty("DOB") public LocalDate getDob() { return dob; } @JsonProperty("FirstName") public String getFirstName() { return firstName; } @JsonProperty("LastName") public String getLastName() { return lastName; } @JsonProperty("GovId") public String getGovId() { return govId; } @JsonProperty("GovIdType") public String getGovIdType() { return govIdType; } /** * This returns the unique document ID given a specific government ID. * * @param txn * A transaction executor object. * @param govId * The government ID of a driver. * @return the unique document ID. */ public static String getDocumentIdByGovId(final TransactionExecutor txn, final String govId) { return SampleData.getDocumentId(txn, Constants.PERSON_TABLE_NAME, "GovId", govId); } @Override public String toString() { return "Person{" + "firstName='" + firstName + '\'' + ", lastName='" + lastName + '\'' + ", dob=" + dob + ", govId='" + govId + '\'' + ", govIdType='" + govIdType + '\'' + ", address='" + address + '\'' + '}'; } }
    3. VehicleRegistration.java

      /* * Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: MIT-0 * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * software and associated documentation files (the "Software"), to deal in the Software * without restriction, including without limitation the rights to use, copy, modify, * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package software.amazon.qldb.tutorial.model; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import software.amazon.qldb.TransactionExecutor; import software.amazon.qldb.tutorial.Constants; import software.amazon.qldb.tutorial.model.streams.RevisionData; import java.math.BigDecimal; import java.time.LocalDate; /** * Represents a vehicle registration, serializable to (and from) Ion. */ public final class VehicleRegistration implements RevisionData { private final String vin; private final String licensePlateNumber; private final String state; private final String city; private final BigDecimal pendingPenaltyTicketAmount; private final LocalDate validFromDate; private final LocalDate validToDate; private final Owners owners; @JsonCreator public VehicleRegistration(@JsonProperty("VIN") final String vin, @JsonProperty("LicensePlateNumber") final String licensePlateNumber, @JsonProperty("State") final String state, @JsonProperty("City") final String city, @JsonProperty("PendingPenaltyTicketAmount") final BigDecimal pendingPenaltyTicketAmount, @JsonProperty("ValidFromDate") final LocalDate validFromDate, @JsonProperty("ValidToDate") final LocalDate validToDate, @JsonProperty("Owners") final Owners owners) { this.vin = vin; this.licensePlateNumber = licensePlateNumber; this.state = state; this.city = city; this.pendingPenaltyTicketAmount = pendingPenaltyTicketAmount; this.validFromDate = validFromDate; this.validToDate = validToDate; this.owners = owners; } @JsonProperty("City") public String getCity() { return city; } @JsonProperty("LicensePlateNumber") public String getLicensePlateNumber() { return licensePlateNumber; } @JsonProperty("Owners") public Owners getOwners() { return owners; } @JsonProperty("PendingPenaltyTicketAmount") public BigDecimal getPendingPenaltyTicketAmount() { return pendingPenaltyTicketAmount; } @JsonProperty("State") public String getState() { return state; } @JsonProperty("ValidFromDate") @JsonSerialize(using = IonLocalDateSerializer.class) @JsonDeserialize(using = IonLocalDateDeserializer.class) public LocalDate getValidFromDate() { return validFromDate; } @JsonProperty("ValidToDate") @JsonSerialize(using = IonLocalDateSerializer.class) @JsonDeserialize(using = IonLocalDateDeserializer.class) public LocalDate getValidToDate() { return validToDate; } @JsonProperty("VIN") public String getVin() { return vin; } /** * Returns the unique document ID of a vehicle given a specific VIN. * * @param txn * A transaction executor object. * @param vin * The VIN of a vehicle. * @return the unique document ID of the specified vehicle. */ public static String getDocumentIdByVin(final TransactionExecutor txn, final String vin) { return SampleData.getDocumentId(txn, Constants.VEHICLE_REGISTRATION_TABLE_NAME, "VIN", vin); } @Override public String toString() { return "VehicleRegistration{" + "vin='" + vin + '\'' + ", licensePlateNumber='" + licensePlateNumber + '\'' + ", state='" + state + '\'' + ", city='" + city + '\'' + ", pendingPenaltyTicketAmount=" + pendingPenaltyTicketAmount + ", validFromDate=" + validFromDate + ", validToDate=" + validToDate + ", owners=" + owners + '}'; } }
    4. Vehicle.java

      /* * Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: MIT-0 * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * software and associated documentation files (the "Software"), to deal in the Software * without restriction, including without limitation the rights to use, copy, modify, * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package software.amazon.qldb.tutorial.model; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import software.amazon.qldb.tutorial.model.streams.RevisionData; /** * Represents a vehicle, serializable to (and from) Ion. */ public final class Vehicle implements RevisionData { private final String vin; private final String type; private final int year; private final String make; private final String model; private final String color; @JsonCreator public Vehicle(@JsonProperty("VIN") final String vin, @JsonProperty("Type") final String type, @JsonProperty("Year") final int year, @JsonProperty("Make") final String make, @JsonProperty("Model") final String model, @JsonProperty("Color") final String color) { this.vin = vin; this.type = type; this.year = year; this.make = make; this.model = model; this.color = color; } @JsonProperty("Color") public String getColor() { return color; } @JsonProperty("Make") public String getMake() { return make; } @JsonProperty("Model") public String getModel() { return model; } @JsonProperty("Type") public String getType() { return type; } @JsonProperty("VIN") public String getVin() { return vin; } @JsonProperty("Year") public int getYear() { return year; } @Override public String toString() { return "Vehicle{" + "vin='" + vin + '\'' + ", type='" + type + '\'' + ", year=" + year + ", make='" + make + '\'' + ", model='" + model + '\'' + ", color='" + color + '\'' + '}'; } }
    5. Owner.java

      /* * Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: MIT-0 * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * software and associated documentation files (the "Software"), to deal in the Software * without restriction, including without limitation the rights to use, copy, modify, * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package software.amazon.qldb.tutorial.model; import com.fasterxml.jackson.annotation.JsonProperty; /** * Represents a vehicle owner, serializable to (and from) Ion. */ public final class Owner { private final String personId; public Owner(@JsonProperty("PersonId") final String personId) { this.personId = personId; } @JsonProperty("PersonId") public String getPersonId() { return personId; } @Override public String toString() { return "Owner{" + "personId='" + personId + '\'' + '}'; } }
    6. Owners.java

      /* * Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: MIT-0 * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * software and associated documentation files (the "Software"), to deal in the Software * without restriction, including without limitation the rights to use, copy, modify, * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package software.amazon.qldb.tutorial.model; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.List; /** * Represents a set of owners for a given vehicle, serializable to (and from) Ion. */ public final class Owners { private final Owner primaryOwner; private final List<Owner> secondaryOwners; public Owners(@JsonProperty("PrimaryOwner") final Owner primaryOwner, @JsonProperty("SecondaryOwners") final List<Owner> secondaryOwners) { this.primaryOwner = primaryOwner; this.secondaryOwners = secondaryOwners; } @JsonProperty("PrimaryOwner") public Owner getPrimaryOwner() { return primaryOwner; } @JsonProperty("SecondaryOwners") public List<Owner> getSecondaryOwners() { return secondaryOwners; } @Override public String toString() { return "Owners{" + "primaryOwner=" + primaryOwner + ", secondaryOwners=" + secondaryOwners + '}'; } }
    7. DmlResultDocument.java

      /* * Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: MIT-0 * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * software and associated documentation files (the "Software"), to deal in the Software * without restriction, including without limitation the rights to use, copy, modify, * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package software.amazon.qldb.tutorial.qldb; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; /** * Contains information about an individual document inserted or modified * as a result of DML. */ public class DmlResultDocument { private String documentId; @JsonCreator public DmlResultDocument(@JsonProperty("documentId") final String documentId) { this.documentId = documentId; } public String getDocumentId() { return documentId; } @Override public String toString() { return "DmlResultDocument{" + "documentId='" + documentId + '\'' + '}'; } }
    8. IonLocalDateDeserializer.java

      /* * Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: MIT-0 * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * software and associated documentation files (the "Software"), to deal in the Software * without restriction, including without limitation the rights to use, copy, modify, * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package software.amazon.qldb.tutorial.model; import com.amazon.ion.Timestamp; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.JsonDeserializer; import java.io.IOException; import java.time.LocalDate; /** * Deserializes [java.time.LocalDate] from Ion. */ public class IonLocalDateDeserializer extends JsonDeserializer<LocalDate> { @Override public LocalDate deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException { return timestampToLocalDate((Timestamp) jp.getEmbeddedObject()); } private LocalDate timestampToLocalDate(Timestamp timestamp) { return LocalDate.of(timestamp.getYear(), timestamp.getMonth(), timestamp.getDay()); } }
    9. IonLocalDateSerializer.java

      /* * Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: MIT-0 * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * software and associated documentation files (the "Software"), to deal in the Software * without restriction, including without limitation the rights to use, copy, modify, * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package software.amazon.qldb.tutorial.model; import com.amazon.ion.Timestamp; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.SerializerProvider; import com.fasterxml.jackson.databind.ser.std.StdScalarSerializer; import com.fasterxml.jackson.dataformat.ion.IonGenerator; import java.io.IOException; import java.time.LocalDate; /** * Serializes [java.time.LocalDate] to Ion. */ public class IonLocalDateSerializer extends StdScalarSerializer<LocalDate> { public IonLocalDateSerializer() { super(LocalDate.class); } @Override public void serialize(LocalDate date, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException { Timestamp timestamp = Timestamp.forDay(date.getYear(), date.getMonthValue(), date.getDayOfMonth()); ((IonGenerator) jsonGenerator).writeValue(timestamp); } }
    10. RevisionData.java

      /* * Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: MIT-0 * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * software and associated documentation files (the "Software"), to deal in the Software * without restriction, including without limitation the rights to use, copy, modify, * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package software.amazon.qldb.tutorial.model.streams; /** * Allows modeling the content of all revisions as a generic revision data. Used * in the {@link Revision} and extended by domain models in {@link * software.amazon.qldb.tutorial.model} to make it easier to write the {@link * Revision.RevisionDataDeserializer} that must deserialize the {@link * Revision#data} from different domain models. */ public interface RevisionData { }
  2. Review the following file (SampleData.java), which represents the sample data that you insert into the vehicle-registration tables.

    2.x
    /* * Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: MIT-0 * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * software and associated documentation files (the "Software"), to deal in the Software * without restriction, including without limitation the rights to use, copy, modify, * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package software.amazon.qldb.tutorial.model; import com.amazon.ion.IonString; import com.amazon.ion.IonStruct; import com.amazon.ion.IonValue; import java.io.IOException; import java.math.BigDecimal; import java.text.ParseException; import java.time.LocalDate; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import software.amazon.qldb.Result; import software.amazon.qldb.TransactionExecutor; import software.amazon.qldb.tutorial.ConnectToLedger; import software.amazon.qldb.tutorial.Constants; import software.amazon.qldb.tutorial.qldb.DmlResultDocument; import software.amazon.qldb.tutorial.qldb.QldbRevision; /** * Sample domain objects for use throughout this tutorial. */ public final class SampleData { public static final DateTimeFormatter DATE_TIME_FORMAT = DateTimeFormatter.ofPattern("yyyy-MM-dd"); public static final List<VehicleRegistration> REGISTRATIONS = Collections.unmodifiableList(Arrays.asList( new VehicleRegistration("1N4AL11D75C109151", "LEWISR261LL", "WA", "Seattle", BigDecimal.valueOf(90.25), convertToLocalDate("2017-08-21"), convertToLocalDate("2020-05-11"), new Owners(new Owner(null), Collections.emptyList())), new VehicleRegistration("KM8SRDHF6EU074761", "CA762X", "WA", "Kent", BigDecimal.valueOf(130.75), convertToLocalDate("2017-09-14"), convertToLocalDate("2020-06-25"), new Owners(new Owner(null), Collections.emptyList())), new VehicleRegistration("3HGGK5G53FM761765", "CD820Z", "WA", "Everett", BigDecimal.valueOf(442.30), convertToLocalDate("2011-03-17"), convertToLocalDate("2021-03-24"), new Owners(new Owner(null), Collections.emptyList())), new VehicleRegistration("1HVBBAANXWH544237", "LS477D", "WA", "Tacoma", BigDecimal.valueOf(42.20), convertToLocalDate("2011-10-26"), convertToLocalDate("2023-09-25"), new Owners(new Owner(null), Collections.emptyList())), new VehicleRegistration("1C4RJFAG0FC625797", "TH393F", "WA", "Olympia", BigDecimal.valueOf(30.45), convertToLocalDate("2013-09-02"), convertToLocalDate("2024-03-19"), new Owners(new Owner(null), Collections.emptyList())) )); public static final List<Vehicle> VEHICLES = Collections.unmodifiableList(Arrays.asList( new Vehicle("1N4AL11D75C109151", "Sedan", 2011, "Audi", "A5", "Silver"), new Vehicle("KM8SRDHF6EU074761", "Sedan", 2015, "Tesla", "Model S", "Blue"), new Vehicle("3HGGK5G53FM761765", "Motorcycle", 2011, "Ducati", "Monster 1200", "Yellow"), new Vehicle("1HVBBAANXWH544237", "Semi", 2009, "Ford", "F 150", "Black"), new Vehicle("1C4RJFAG0FC625797", "Sedan", 2019, "Mercedes", "CLK 350", "White") )); public static final List<Person> PEOPLE = Collections.unmodifiableList(Arrays.asList( new Person("Raul", "Lewis", convertToLocalDate("1963-08-19"), "LEWISR261LL", "Driver License", "1719 University Street, Seattle, WA, 98109"), new Person("Brent", "Logan", convertToLocalDate("1967-07-03"), "LOGANB486CG", "Driver License", "43 Stockert Hollow Road, Everett, WA, 98203"), new Person("Alexis", "Pena", convertToLocalDate("1974-02-10"), "744 849 301", "SSN", "4058 Melrose Street, Spokane Valley, WA, 99206"), new Person("Melvin", "Parker", convertToLocalDate("1976-05-22"), "P626-168-229-765", "Passport", "4362 Ryder Avenue, Seattle, WA, 98101"), new Person("Salvatore", "Spencer", convertToLocalDate("1997-11-15"), "S152-780-97-415-0", "Passport", "4450 Honeysuckle Lane, Seattle, WA, 98101") )); public static final List<DriversLicense> LICENSES = Collections.unmodifiableList(Arrays.asList( new DriversLicense(null, "LEWISR261LL", "Learner", convertToLocalDate("2016-12-20"), convertToLocalDate("2020-11-15")), new DriversLicense(null, "LOGANB486CG", "Probationary", convertToLocalDate("2016-04-06"), convertToLocalDate("2020-11-15")), new DriversLicense(null, "744 849 301", "Full", convertToLocalDate("2017-12-06"), convertToLocalDate("2022-10-15")), new DriversLicense(null, "P626-168-229-765", "Learner", convertToLocalDate("2017-08-16"), convertToLocalDate("2021-11-15")), new DriversLicense(null, "S152-780-97-415-0", "Probationary", convertToLocalDate("2015-08-15"), convertToLocalDate("2021-08-21")) )); private SampleData() { } /** * Converts a date string with the format 'yyyy-MM-dd' into a {@link java.util.Date} object. * * @param date * The date string to convert. * @return {@link java.time.LocalDate} or null if there is a {@link ParseException} */ public static synchronized LocalDate convertToLocalDate(String date) { return LocalDate.parse(date, DATE_TIME_FORMAT); } /** * Convert the result set into a list of IonValues. * * @param result * The result set to convert. * @return a list of IonValues. */ public static List<IonValue> toIonValues(Result result) { final List<IonValue> valueList = new ArrayList<>(); result.iterator().forEachRemaining(valueList::add); return valueList; } /** * Get the document ID of a particular document. * * @param txn * A transaction executor object. * @param tableName * Name of the table containing the document. * @param identifier * The identifier used to narrow down the search. * @param value * Value of the identifier. * @return the list of document IDs in the result set. */ public static String getDocumentId(final TransactionExecutor txn, final String tableName, final String identifier, final String value) { try { final List<IonValue> parameters = Collections.singletonList(Constants.MAPPER.writeValueAsIonValue(value)); final String query = String.format("SELECT metadata.id FROM _ql_committed_%s AS p WHERE p.data.%s = ?", tableName, identifier); Result result = txn.execute(query, parameters); if (result.isEmpty()) { throw new IllegalStateException("Unable to retrieve document ID using " + value); } return getStringValueOfStructField((IonStruct) result.iterator().next(), "id"); } catch (IOException ioe) { throw new IllegalStateException(ioe); } } /** * Get the document by ID. * * @param tableName * Name of the table to insert documents into. * @param documentId * The unique ID of a document in the Person table. * @return a {@link QldbRevision} object. * @throws IllegalStateException if failed to convert parameter into {@link IonValue}. */ public static QldbRevision getDocumentById(String tableName, String documentId) { try { final IonValue ionValue = Constants.MAPPER.writeValueAsIonValue(documentId); Result result = ConnectToLedger.getDriver().execute(txn -> { return txn.execute("SELECT c.* FROM _ql_committed_" + tableName + " AS c BY docId " + "WHERE docId = ?", ionValue); }); if (result.isEmpty()) { throw new IllegalStateException("Unable to retrieve document by id " + documentId + " in table " + tableName); } return Constants.MAPPER.readValue(result.iterator().next(), QldbRevision.class); } catch (IOException ioe) { throw new IllegalStateException(ioe); } } /** * Return a list of modified document IDs as strings from a DML {@link Result}. * * @param result * The result set from a DML operation. * @return the list of document IDs modified by the operation. */ public static List<String> getDocumentIdsFromDmlResult(final Result result) { final List<String> strings = new ArrayList<>(); result.iterator().forEachRemaining(row -> strings.add(getDocumentIdFromDmlResultDocument(row))); return strings; } /** * Convert the given DML result row's document ID to string. * * @param dmlResultDocument * The {@link IonValue} representing the results of a DML operation. * @return a string of document ID. */ public static String getDocumentIdFromDmlResultDocument(final IonValue dmlResultDocument) { try { DmlResultDocument result = Constants.MAPPER.readValue(dmlResultDocument, DmlResultDocument.class); return result.getDocumentId(); } catch (IOException ioe) { throw new IllegalStateException(ioe); } } /** * Get the String value of a given {@link IonStruct} field name. * @param struct the {@link IonStruct} from which to get the value. * @param fieldName the name of the field from which to get the value. * @return the String value of the field within the given {@link IonStruct}. */ public static String getStringValueOfStructField(final IonStruct struct, final String fieldName) { return ((IonString) struct.get(fieldName)).stringValue(); } /** * Return a copy of the given driver's license with updated person Id. * * @param oldLicense * The old driver's license to update. * @param personId * The PersonId of the driver. * @return the updated {@link DriversLicense}. */ public static DriversLicense updatePersonIdDriversLicense(final DriversLicense oldLicense, final String personId) { return new DriversLicense(personId, oldLicense.getLicenseNumber(), oldLicense.getLicenseType(), oldLicense.getValidFromDate(), oldLicense.getValidToDate()); } /** * Return a copy of the given vehicle registration with updated person Id. * * @param oldRegistration * The old vehicle registration to update. * @param personId * The PersonId of the driver. * @return the updated {@link VehicleRegistration}. */ public static VehicleRegistration updateOwnerVehicleRegistration(final VehicleRegistration oldRegistration, final String personId) { return new VehicleRegistration(oldRegistration.getVin(), oldRegistration.getLicensePlateNumber(), oldRegistration.getState(), oldRegistration.getCity(), oldRegistration.getPendingPenaltyTicketAmount(), oldRegistration.getValidFromDate(), oldRegistration.getValidToDate(), new Owners(new Owner(personId), Collections.emptyList())); } }
    1.x
    /* * Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: MIT-0 * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * software and associated documentation files (the "Software"), to deal in the Software * without restriction, including without limitation the rights to use, copy, modify, * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package software.amazon.qldb.tutorial.model; import com.amazon.ion.IonString; import com.amazon.ion.IonStruct; import com.amazon.ion.IonValue; import software.amazon.qldb.QldbSession; import software.amazon.qldb.Result; import software.amazon.qldb.TransactionExecutor; import software.amazon.qldb.tutorial.Constants; import software.amazon.qldb.tutorial.qldb.DmlResultDocument; import software.amazon.qldb.tutorial.qldb.QldbRevision; import java.io.IOException; import java.math.BigDecimal; import java.text.ParseException; import java.time.LocalDate; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; /** * Sample domain objects for use throughout this tutorial. */ public final class SampleData { public static final DateTimeFormatter DATE_TIME_FORMAT = DateTimeFormatter.ofPattern("yyyy-MM-dd"); public static final List<VehicleRegistration> REGISTRATIONS = Collections.unmodifiableList(Arrays.asList( new VehicleRegistration("1N4AL11D75C109151", "LEWISR261LL", "WA", "Seattle", BigDecimal.valueOf(90.25), convertToLocalDate("2017-08-21"), convertToLocalDate("2020-05-11"), new Owners(new Owner(null), Collections.emptyList())), new VehicleRegistration("KM8SRDHF6EU074761", "CA762X", "WA", "Kent", BigDecimal.valueOf(130.75), convertToLocalDate("2017-09-14"), convertToLocalDate("2020-06-25"), new Owners(new Owner(null), Collections.emptyList())), new VehicleRegistration("3HGGK5G53FM761765", "CD820Z", "WA", "Everett", BigDecimal.valueOf(442.30), convertToLocalDate("2011-03-17"), convertToLocalDate("2021-03-24"), new Owners(new Owner(null), Collections.emptyList())), new VehicleRegistration("1HVBBAANXWH544237", "LS477D", "WA", "Tacoma", BigDecimal.valueOf(42.20), convertToLocalDate("2011-10-26"), convertToLocalDate("2023-09-25"), new Owners(new Owner(null), Collections.emptyList())), new VehicleRegistration("1C4RJFAG0FC625797", "TH393F", "WA", "Olympia", BigDecimal.valueOf(30.45), convertToLocalDate("2013-09-02"), convertToLocalDate("2024-03-19"), new Owners(new Owner(null), Collections.emptyList())) )); public static final List<Vehicle> VEHICLES = Collections.unmodifiableList(Arrays.asList( new Vehicle("1N4AL11D75C109151", "Sedan", 2011, "Audi", "A5", "Silver"), new Vehicle("KM8SRDHF6EU074761", "Sedan", 2015, "Tesla", "Model S", "Blue"), new Vehicle("3HGGK5G53FM761765", "Motorcycle", 2011, "Ducati", "Monster 1200", "Yellow"), new Vehicle("1HVBBAANXWH544237", "Semi", 2009, "Ford", "F 150", "Black"), new Vehicle("1C4RJFAG0FC625797", "Sedan", 2019, "Mercedes", "CLK 350", "White") )); public static final List<Person> PEOPLE = Collections.unmodifiableList(Arrays.asList( new Person("Raul", "Lewis", convertToLocalDate("1963-08-19"), "LEWISR261LL", "Driver License", "1719 University Street, Seattle, WA, 98109"), new Person("Brent", "Logan", convertToLocalDate("1967-07-03"), "LOGANB486CG", "Driver License", "43 Stockert Hollow Road, Everett, WA, 98203"), new Person("Alexis", "Pena", convertToLocalDate("1974-02-10"), "744 849 301", "SSN", "4058 Melrose Street, Spokane Valley, WA, 99206"), new Person("Melvin", "Parker", convertToLocalDate("1976-05-22"), "P626-168-229-765", "Passport", "4362 Ryder Avenue, Seattle, WA, 98101"), new Person("Salvatore", "Spencer", convertToLocalDate("1997-11-15"), "S152-780-97-415-0", "Passport", "4450 Honeysuckle Lane, Seattle, WA, 98101") )); public static final List<DriversLicense> LICENSES = Collections.unmodifiableList(Arrays.asList( new DriversLicense(null, "LEWISR261LL", "Learner", convertToLocalDate("2016-12-20"), convertToLocalDate("2020-11-15")), new DriversLicense(null, "LOGANB486CG", "Probationary", convertToLocalDate("2016-04-06"), convertToLocalDate("2020-11-15")), new DriversLicense(null, "744 849 301", "Full", convertToLocalDate("2017-12-06"), convertToLocalDate("2022-10-15")), new DriversLicense(null, "P626-168-229-765", "Learner", convertToLocalDate("2017-08-16"), convertToLocalDate("2021-11-15")), new DriversLicense(null, "S152-780-97-415-0", "Probationary", convertToLocalDate("2015-08-15"), convertToLocalDate("2021-08-21")) )); private SampleData() { } /** * Converts a date string with the format 'yyyy-MM-dd' into a {@link java.util.Date} object. * * @param date * The date string to convert. * @return {@link LocalDate} or null if there is a {@link ParseException} */ public static synchronized LocalDate convertToLocalDate(String date) { return LocalDate.parse(date, DATE_TIME_FORMAT); } /** * Convert the result set into a list of IonValues. * * @param result * The result set to convert. * @return a list of IonValues. */ public static List<IonValue> toIonValues(Result result) { final List<IonValue> valueList = new ArrayList<>(); result.iterator().forEachRemaining(valueList::add); return valueList; } /** * Get the document ID of a particular document. * * @param txn * A transaction executor object. * @param tableName * Name of the table containing the document. * @param identifier * The identifier used to narrow down the search. * @param value * Value of the identifier. * @return the list of document IDs in the result set. */ public static String getDocumentId(final TransactionExecutor txn, final String tableName, final String identifier, final String value) { try { final List<IonValue> parameters = Collections.singletonList(Constants.MAPPER.writeValueAsIonValue(value)); final String query = String.format("SELECT metadata.id FROM _ql_committed_%s AS p WHERE p.data.%s = ?", tableName, identifier); Result result = txn.execute(query, parameters); if (result.isEmpty()) { throw new IllegalStateException("Unable to retrieve document ID using " + value); } return getStringValueOfStructField((IonStruct) result.iterator().next(), "id"); } catch (IOException ioe) { throw new IllegalStateException(ioe); } } /** * Get the document by ID. * * @param qldbSession * A QLDB session. * @param tableName * Name of the table to insert documents into. * @param documentId * The unique ID of a document in the Person table. * @return a {@link QldbRevision} object. * @throws IllegalStateException if failed to convert parameter into {@link IonValue}. */ public static QldbRevision getDocumentById(QldbSession qldbSession, String tableName, String documentId) { try { final List<IonValue> parameters = Collections.singletonList(Constants.MAPPER.writeValueAsIonValue(documentId)); final String query = String.format("SELECT c.* FROM _ql_committed_%s AS c BY docId WHERE docId = ?", tableName); Result result = qldbSession.execute(query, parameters); if (result.isEmpty()) { throw new IllegalStateException("Unable to retrieve document by id " + documentId + " in table " + tableName); } return Constants.MAPPER.readValue(result.iterator().next(), QldbRevision.class); } catch (IOException ioe) { throw new IllegalStateException(ioe); } } /** * Return a list of modified document IDs as strings from a DML {@link Result}. * * @param result * The result set from a DML operation. * @return the list of document IDs modified by the operation. */ public static List<String> getDocumentIdsFromDmlResult(final Result result) { final List<String> strings = new ArrayList<>(); result.iterator().forEachRemaining(row -> strings.add(getDocumentIdFromDmlResultDocument(row))); return strings; } /** * Convert the given DML result row's document ID to string. * * @param dmlResultDocument * The {@link IonValue} representing the results of a DML operation. * @return a string of document ID. */ public static String getDocumentIdFromDmlResultDocument(final IonValue dmlResultDocument) { try { DmlResultDocument result = Constants.MAPPER.readValue(dmlResultDocument, DmlResultDocument.class); return result.getDocumentId(); } catch (IOException ioe) { throw new IllegalStateException(ioe); } } /** * Get the String value of a given {@link IonStruct} field name. * @param struct the {@link IonStruct} from which to get the value. * @param fieldName the name of the field from which to get the value. * @return the String value of the field within the given {@link IonStruct}. */ public static String getStringValueOfStructField(final IonStruct struct, final String fieldName) { return ((IonString) struct.get(fieldName)).stringValue(); } /** * Return a copy of the given driver's license with updated person Id. * * @param oldLicense * The old driver's license to update. * @param personId * The PersonId of the driver. * @return the updated {@link DriversLicense}. */ public static DriversLicense updatePersonIdDriversLicense(final DriversLicense oldLicense, final String personId) { return new DriversLicense(personId, oldLicense.getLicenseNumber(), oldLicense.getLicenseType(), oldLicense.getValidFromDate(), oldLicense.getValidToDate()); } /** * Return a copy of the given vehicle registration with updated person Id. * * @param oldRegistration * The old vehicle registration to update. * @param personId * The PersonId of the driver. * @return the updated {@link VehicleRegistration}. */ public static VehicleRegistration updateOwnerVehicleRegistration(final VehicleRegistration oldRegistration, final String personId) { return new VehicleRegistration(oldRegistration.getVin(), oldRegistration.getLicensePlateNumber(), oldRegistration.getState(), oldRegistration.getCity(), oldRegistration.getPendingPenaltyTicketAmount(), oldRegistration.getValidFromDate(), oldRegistration.getValidToDate(), new Owners(new Owner(personId), Collections.emptyList())); } }
    Important

    For the Amazon Ion package, you must use the namespace com.amazon.ion in your application. The AWS SDK for Java depends on another Ion package under the namespace software.amazon.ion, but this is a legacy package that is not compatible with the QLDB driver.

    Note
    • This class uses Ion libraries to provide helper methods that convert your data to and from Ion format.

    • The getDocumentId method runs a query on a table with the prefix _ql_committed_. This is a reserved prefix signifying that you want to query the committed view of a table. In this view, your data is nested in the data field, and metadata is nested in the metadata field.

  3. Compile and run the following program (CreateTable.java) to create the previously mentioned tables.

    2.x
    /* * Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: MIT-0 * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * software and associated documentation files (the "Software"), to deal in the Software * without restriction, including without limitation the rights to use, copy, modify, * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package software.amazon.qldb.tutorial; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import software.amazon.qldb.Result; import software.amazon.qldb.TransactionExecutor; import software.amazon.qldb.tutorial.model.SampleData; /** * Create tables in a QLDB ledger. * * This code expects that you have AWS credentials setup per: * http://docs.aws.amazon.com/java-sdk/latest/developer-guide/setup-credentials.html */ public final class CreateTable { public static final Logger log = LoggerFactory.getLogger(CreateTable.class); private CreateTable() { } /** * Registrations, vehicles, owners, and licenses tables being created in a single transaction. * * @param txn * The {@link TransactionExecutor} for lambda execute. * @param tableName * Name of the table to be created. * @return the number of tables created. */ public static int createTable(final TransactionExecutor txn, final String tableName) { log.info("Creating the '{}' table...", tableName); final String createTable = String.format("CREATE TABLE %s", tableName); final Result result = txn.execute(createTable); log.info("{} table created successfully.", tableName); return SampleData.toIonValues(result).size(); } public static void main(final String... args) { ConnectToLedger.getDriver().execute(txn -> { createTable(txn, Constants.DRIVERS_LICENSE_TABLE_NAME); createTable(txn, Constants.PERSON_TABLE_NAME); createTable(txn, Constants.VEHICLE_TABLE_NAME); createTable(txn, Constants.VEHICLE_REGISTRATION_TABLE_NAME); }); } }
    1.x
    /* * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: MIT-0 * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * software and associated documentation files (the "Software"), to deal in the Software * without restriction, including without limitation the rights to use, copy, modify, * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package software.amazon.qldb.tutorial; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import software.amazon.qldb.Result; import software.amazon.qldb.TransactionExecutor; import software.amazon.qldb.tutorial.model.SampleData; /** * Create tables in a QLDB ledger. * * This code expects that you have AWS credentials setup per: * http://docs.aws.amazon.com/java-sdk/latest/developer-guide/setup-credentials.html */ public final class CreateTable { public static final Logger log = LoggerFactory.getLogger(CreateTable.class); private CreateTable() { } /** * Registrations, vehicles, owners, and licenses tables being created in a single transaction. * * @param txn * The {@link TransactionExecutor} for lambda execute. * @param tableName * Name of the table to be created. * @return the number of tables created. */ public static int createTable(final TransactionExecutor txn, final String tableName) { log.info("Creating the '{}' table...", tableName); final String createTable = String.format("CREATE TABLE %s", tableName); final Result result = txn.execute(createTable); log.info("{} table created successfully.", tableName); return SampleData.toIonValues(result).size(); } public static void main(final String... args) { ConnectToLedger.getDriver().execute(txn -> { createTable(txn, Constants.DRIVERS_LICENSE_TABLE_NAME); createTable(txn, Constants.PERSON_TABLE_NAME); createTable(txn, Constants.VEHICLE_TABLE_NAME); createTable(txn, Constants.VEHICLE_REGISTRATION_TABLE_NAME); }, (retryAttempt) -> log.info("Retrying due to OCC conflict...")); } }
    Note

    This program demonstrates how to pass a TransactionExecutor lambda to the execute method. In this example, you run multiple CREATE TABLE PartiQL statements in a single transaction by using a lambda expression.

    The execute method implicitly starts a transaction, runs all of the statements in the lambda, and then auto-commits the transaction.

  4. Compile and run the following program (CreateIndex.java) to create indexes on the tables, as previously described.

    2.x
    /* * Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: MIT-0 * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * software and associated documentation files (the "Software"), to deal in the Software * without restriction, including without limitation the rights to use, copy, modify, * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package software.amazon.qldb.tutorial; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import software.amazon.qldb.Result; import software.amazon.qldb.TransactionExecutor; import software.amazon.qldb.tutorial.model.SampleData; /** * Create indexes on tables in a particular ledger. * * This code expects that you have AWS credentials setup per: * http://docs.aws.amazon.com/java-sdk/latest/developer-guide/setup-credentials.html */ public final class CreateIndex { public static final Logger log = LoggerFactory.getLogger(CreateIndex.class); private CreateIndex() { } /** * In this example, create indexes for registrations and vehicles tables. * * @param txn * The {@link TransactionExecutor} for lambda execute. * @param tableName * Name of the table to be created. * @param indexAttribute * The index attribute to use. * @return the number of tables created. */ public static int createIndex(final TransactionExecutor txn, final String tableName, final String indexAttribute) { log.info("Creating an index on {}...", indexAttribute); final String createIndex = String.format("CREATE INDEX ON %s (%s)", tableName, indexAttribute); final Result r = txn.execute(createIndex); return SampleData.toIonValues(r).size(); } public static void main(final String... args) { ConnectToLedger.getDriver().execute(txn -> { createIndex(txn, Constants.PERSON_TABLE_NAME, Constants.PERSON_GOV_ID_INDEX_NAME); createIndex(txn, Constants.VEHICLE_TABLE_NAME, Constants.VIN_INDEX_NAME); createIndex(txn, Constants.DRIVERS_LICENSE_TABLE_NAME, Constants.DRIVER_LICENSE_NUMBER_INDEX_NAME); createIndex(txn, Constants.DRIVERS_LICENSE_TABLE_NAME, Constants.DRIVER_LICENSE_PERSONID_INDEX_NAME); createIndex(txn, Constants.VEHICLE_REGISTRATION_TABLE_NAME, Constants.VIN_INDEX_NAME); createIndex(txn, Constants.VEHICLE_REGISTRATION_TABLE_NAME, Constants.VEHICLE_REGISTRATION_LICENSE_PLATE_NUMBER_INDEX_NAME); }); log.info("Indexes created successfully!"); } }
    1.x
    /* * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: MIT-0 * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * software and associated documentation files (the "Software"), to deal in the Software * without restriction, including without limitation the rights to use, copy, modify, * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package software.amazon.qldb.tutorial; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import software.amazon.qldb.Result; import software.amazon.qldb.TransactionExecutor; import software.amazon.qldb.tutorial.model.SampleData; /** * Create indexes on tables in a particular ledger. * * This code expects that you have AWS credentials setup per: * http://docs.aws.amazon.com/java-sdk/latest/developer-guide/setup-credentials.html */ public final class CreateIndex { public static final Logger log = LoggerFactory.getLogger(CreateIndex.class); private CreateIndex() { } /** * In this example, create indexes for registrations and vehicles tables. * * @param txn * The {@link TransactionExecutor} for lambda execute. * @param tableName * Name of the table to be created. * @param indexAttribute * The index attribute to use. * @return the number of tables created. */ public static int createIndex(final TransactionExecutor txn, final String tableName, final String indexAttribute) { log.info("Creating an index on {}...", indexAttribute); final String createIndex = String.format("CREATE INDEX ON %s (%s)", tableName, indexAttribute); final Result r = txn.execute(createIndex); return SampleData.toIonValues(r).size(); } public static void main(final String... args) { ConnectToLedger.getDriver().execute(txn -> { createIndex(txn, Constants.PERSON_TABLE_NAME, Constants.PERSON_GOV_ID_INDEX_NAME); createIndex(txn, Constants.VEHICLE_TABLE_NAME, Constants.VIN_INDEX_NAME); createIndex(txn, Constants.DRIVERS_LICENSE_TABLE_NAME, Constants.DRIVER_LICENSE_NUMBER_INDEX_NAME); createIndex(txn, Constants.DRIVERS_LICENSE_TABLE_NAME, Constants.DRIVER_LICENSE_PERSONID_INDEX_NAME); createIndex(txn, Constants.VEHICLE_REGISTRATION_TABLE_NAME, Constants.VIN_INDEX_NAME); createIndex(txn, Constants.VEHICLE_REGISTRATION_TABLE_NAME, Constants.VEHICLE_REGISTRATION_LICENSE_PLATE_NUMBER_INDEX_NAME); }, (retryAttempt) -> log.info("Retrying due to OCC conflict...")); log.info("Indexes created successfully!"); } }
  5. Compile and run the following program (InsertDocument.java) to insert the sample data into your tables.

    2.x
    /* * Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: MIT-0 * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * software and associated documentation files (the "Software"), to deal in the Software * without restriction, including without limitation the rights to use, copy, modify, * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package software.amazon.qldb.tutorial; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.amazon.ion.IonValue; import software.amazon.qldb.TransactionExecutor; import software.amazon.qldb.tutorial.model.DriversLicense; import software.amazon.qldb.tutorial.model.SampleData; import software.amazon.qldb.tutorial.model.VehicleRegistration; /** * Insert documents into a table in a QLDB ledger. * * This code expects that you have AWS credentials setup per: * http://docs.aws.amazon.com/java-sdk/latest/developer-guide/setup-credentials.html */ public final class InsertDocument { public static final Logger log = LoggerFactory.getLogger(InsertDocument.class); private InsertDocument() { } /** * Insert the given list of documents into the specified table and return the document IDs of the inserted documents. * * @param txn * The {@link TransactionExecutor} for lambda execute. * @param tableName * Name of the table to insert documents into. * @param documents * List of documents to insert into the specified table. * @return a list of document IDs. * @throws IllegalStateException if failed to convert documents into an {@link IonValue}. */ public static List<String> insertDocuments(final TransactionExecutor txn, final String tableName, final List documents) { log.info("Inserting some documents in the {} table...", tableName); try { final String query = String.format("INSERT INTO %s ?", tableName); final IonValue ionDocuments = Constants.MAPPER.writeValueAsIonValue(documents); return SampleData.getDocumentIdsFromDmlResult(txn.execute(query, ionDocuments)); } catch (IOException ioe) { throw new IllegalStateException(ioe); } } /** * Update PersonIds in driver's licenses and in vehicle registrations using document IDs. * * @param documentIds * List of document IDs representing the PersonIds in DriversLicense and PrimaryOwners in VehicleRegistration. * @param licenses * List of driver's licenses to update. * @param registrations * List of registrations to update. */ public static void updatePersonId(final List<String> documentIds, final List<DriversLicense> licenses, final List<VehicleRegistration> registrations) { for (int i = 0; i < documentIds.size(); ++i) { DriversLicense license = SampleData.LICENSES.get(i); VehicleRegistration registration = SampleData.REGISTRATIONS.get(i); licenses.add(SampleData.updatePersonIdDriversLicense(license, documentIds.get(i))); registrations.add(SampleData.updateOwnerVehicleRegistration(registration, documentIds.get(i))); } } public static void main(final String... args) { final List<DriversLicense> newDriversLicenses = new ArrayList<>(); final List<VehicleRegistration> newVehicleRegistrations = new ArrayList<>(); ConnectToLedger.getDriver().execute(txn -> { List<String> documentIds = insertDocuments(txn, Constants.PERSON_TABLE_NAME, SampleData.PEOPLE); updatePersonId(documentIds, newDriversLicenses, newVehicleRegistrations); insertDocuments(txn, Constants.VEHICLE_TABLE_NAME, SampleData.VEHICLES); insertDocuments(txn, Constants.VEHICLE_REGISTRATION_TABLE_NAME, Collections.unmodifiableList(newVehicleRegistrations)); insertDocuments(txn, Constants.DRIVERS_LICENSE_TABLE_NAME, Collections.unmodifiableList(newDriversLicenses)); }); log.info("Documents inserted successfully!"); } }
    1.x
    /* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: MIT-0 * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * software and associated documentation files (the "Software"), to deal in the Software * without restriction, including without limitation the rights to use, copy, modify, * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package software.amazon.qldb.tutorial; import com.amazon.ion.IonValue; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import software.amazon.qldb.QldbSession; import software.amazon.qldb.TransactionExecutor; import software.amazon.qldb.tutorial.model.DriversLicense; import software.amazon.qldb.tutorial.model.SampleData; import software.amazon.qldb.tutorial.model.VehicleRegistration; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * Insert documents into a table in a QLDB ledger. * * This code expects that you have AWS credentials setup per: * http://docs.aws.amazon.com/java-sdk/latest/developer-guide/setup-credentials.html */ public final class InsertDocument { public static final Logger log = LoggerFactory.getLogger(InsertDocument.class); private InsertDocument() { } /** * Insert the given list of documents into the specified table and return the document IDs of the inserted documents. * * @param txn * The {@link TransactionExecutor} for lambda execute. * @param tableName * Name of the table to insert documents into. * @param documents * List of documents to insert into the specified table. * @return a list of document IDs. * @throws IllegalStateException if failed to convert documents into an {@link IonValue}. */ public static List<String> insertDocuments(final TransactionExecutor txn, final String tableName, final List documents) { log.info("Inserting some documents in the {} table...", tableName); try { final String statement = String.format("INSERT INTO %s ?", tableName); final IonValue ionDocuments = Constants.MAPPER.writeValueAsIonValue(documents); final List<IonValue> parameters = Collections.singletonList(ionDocuments); return SampleData.getDocumentIdsFromDmlResult(txn.execute(statement, parameters)); } catch (IOException ioe) { throw new IllegalStateException(ioe); } } /** * Update PersonIds in driver's licenses and in vehicle registrations using document IDs. * * @param documentIds * List of document IDs representing the PersonIds in DriversLicense and PrimaryOwners in VehicleRegistration. * @param licenses * List of driver's licenses to update. * @param registrations * List of registrations to update. */ public static void updatePersonId(final List<String> documentIds, final List<DriversLicense> licenses, final List<VehicleRegistration> registrations) { for (int i = 0; i < documentIds.size(); ++i) { DriversLicense license = SampleData.LICENSES.get(i); VehicleRegistration registration = SampleData.REGISTRATIONS.get(i); licenses.add(SampleData.updatePersonIdDriversLicense(license, documentIds.get(i))); registrations.add(SampleData.updateOwnerVehicleRegistration(registration, documentIds.get(i))); } } public static void main(final String... args) { final List<DriversLicense> newDriversLicenses = new ArrayList<>(); final List<VehicleRegistration> newVehicleRegistrations = new ArrayList<>(); ConnectToLedger.getDriver().execute(txn -> { List<String> documentIds = insertDocuments(txn, Constants.PERSON_TABLE_NAME, SampleData.PEOPLE); updatePersonId(documentIds, newDriversLicenses, newVehicleRegistrations); insertDocuments(txn, Constants.VEHICLE_TABLE_NAME, SampleData.VEHICLES); insertDocuments(txn, Constants.VEHICLE_REGISTRATION_TABLE_NAME, Collections.unmodifiableList(newVehicleRegistrations)); insertDocuments(txn, Constants.DRIVERS_LICENSE_TABLE_NAME, Collections.unmodifiableList(newDriversLicenses)); }, (retryAttempt) -> log.info("Retrying due to OCC conflict...")); log.info("Documents inserted successfully!"); } }
    Note
    • This program demonstrates how to call the execute method with parameterized values. You can pass data parameters of type IonValue in addition to the PartiQL statement that you want to run. Use a question mark (?) as a variable placeholder in your statement string.

    • If an INSERT statement succeeds, it returns the id of each inserted document.

Next, you can use SELECT statements to read data from the tables in the vehicle-registration ledger. Proceed to Step 4: Query the tables in a ledger.