Quickstart: Build a Java app to manage Azure Cosmos DB Table API data

In this quickstart, you create an Azure Cosmos DB Table API account, and use Data Explorer and a Java app cloned from GitHub to create tables and entities. Azure Cosmos DB is a multi-model database service that lets you quickly create and query document, table, key-value, and graph databases with global distribution and horizontal scale capabilities.

Prerequisites

Create a database account

Important

You need to create a new Table API account to work with the generally available Table API SDKs. Table API accounts created during preview are not supported by the generally available SDKs.

  1. In a new browser window, sign in to the Azure portal.

  2. In the left menu, select Create a resource.

    Create a resource in the Azure portal

  3. On the New page, select Databases > Azure Cosmos DB.

    The Azure portal Databases pane

  4. On the Create Azure Cosmos DB Account page, enter the settings for the new Azure Cosmos DB account.

    Setting Value Description
    Subscription Your subscription Select the Azure subscription that you want to use for this Azure Cosmos DB account.
    Resource Group Create new, then Account Name Select Create new. Then enter a new resource group name for your account. For simplicity, use the same name as your Azure Cosmos DB account name.
    Account Name A unique name Enter a unique name to identify your Azure Cosmos DB account.

    The account name can use only lowercase letters, numbers, and hyphens (-), and must be between 3 and 31 characters long.
    API Table The API determines the type of account to create. Azure Cosmos DB provides five APIs: Core (SQL) for document databases, Gremlin for graph databases, MongoDB for document databases, Azure Table, and Cassandra. You must create a separate account for each API.

    Select Azure Table, because in this quickstart you are creating a table that works with the Table API.

    Learn more about the Table API.
    Location The region closest to your users Select a geographic location to host your Azure Cosmos DB account. Use the location that's closest to your users to give them the fastest access to the data.

    You can leave the Geo-Redundancy and Multi-region Writes options at Disable to avoid additional charges, and skip the Network and Tags sections.

  5. Select Review+Create. After the validation is complete, select Create to create the account.

    The new account page for Azure Cosmos DB

  6. It takes a few minutes to create the account. You'll see a message that states Your deployment is underway. Wait for the deployment to finish, and then select Go to resource.

    The Azure portal notifications pane

Add a table

You can now use the Data Explorer tool in the Azure portal to create a database and table.

  1. Select Data Explorer > New Table.

    The Add Table area is displayed on the far right, you may need to scroll right to see it.

    Data Explorer in the Azure portal

  2. In the Add Table page, enter the settings for the new table.

    Setting Suggested value Description
    Table Id sample-table The ID for your new table. Table names have the same character requirements as database ids. Database names must be between 1 and 255 characters, and cannot contain / \ # ? or a trailing space.
    Throughput 400 RUs Change the throughput to 400 request units per second (RU/s). If you want to reduce latency, you can scale up the throughput later.
  3. Select OK.

  4. Data Explorer displays the new database and table.

    The Azure portal Data Explorer, showing the new database and collection

Add sample data

You can now add data to your new table using Data Explorer.

  1. In Data Explorer, expand sample-table, select Entities, and then select Add Entity.

    Create new entities in Data Explorer in the Azure portal

  2. Now add data to the PartitionKey value box and RowKey value box, and select Add Entity.

    Set the Partition Key and Row Key for a new entity

    You can now add more entities to your table, edit your entities, or query your data in Data Explorer. Data Explorer is also where you can scale your throughput and add stored procedures, user-defined functions, and triggers to your table.

Clone the sample application

Now let's clone a Table app from GitHub, set the connection string, and run it. You'll see how easy it is to work with data programmatically.

  1. Open a command prompt, create a new folder named git-samples, then close the command prompt.

    md "C:\git-samples"
    
  2. Open a git terminal window, such as git bash, and use the cd command to change to the new folder to install the sample app.

    cd "C:\git-samples"
    
  3. Run the following command to clone the sample repository. This command creates a copy of the sample app on your computer.

    git clone https://github.com/Azure-Samples/storage-table-java-getting-started.git 
    

Tip

For a more detailed walkthrough of similar code, see the Cosmos DB Table API sample article.

Review the code

This step is optional. If you're interested in learning how the database resources are created in the code, you can review the following snippets. Otherwise, you can skip ahead to update the connection string section of this doc.

  • The following code shows how to create a table within the Azure Storage:

    private static CloudTable createTable(CloudTableClient tableClient, String tableName) throws StorageException, RuntimeException, IOException, InvalidKeyException,   IllegalArgumentException, URISyntaxException, IllegalStateException {
    
      // Create a new table
      CloudTable table = tableClient.getTableReference(tableName);
      try {
          if (table.createIfNotExists() == false) {
              throw new IllegalStateException(String.format("Table with name \"%s\" already exists.", tableName));
          }
      }
      catch (StorageException s) {
          if (s.getCause() instanceof java.net.ConnectException) {
              System.out.println("Caught connection exception from the client. If running with the default configuration please make sure you have started the storage emulator.");
          }
          throw s;
      }
    
      return table;
    }
    
  • The following code shows how to insert data into the table:

    private static void batchInsertOfCustomerEntities(CloudTable table) throws StorageException {
    
    // Create the batch operation
    TableBatchOperation batchOperation1 = new TableBatchOperation();
    for (int i = 1; i <= 50; i++) {
        CustomerEntity entity = new CustomerEntity("Smith", String.format("%04d", i));
        entity.setEmail(String.format("smith%04d@contoso.com", i));
        entity.setHomePhoneNumber(String.format("425-555-%04d", i));
        entity.setWorkPhoneNumber(String.format("425-556-%04d", i));
        batchOperation1.insertOrMerge(entity);
    }
    
    // Execute the batch operation
    table.execute(batchOperation1);
    }
    
  • The following code shows how to query data from the table:

    private static void partitionScan(CloudTable table, String partitionKey) throws StorageException {
    
        // Create the partition scan query
        TableQuery<CustomerEntity> partitionScanQuery = TableQuery.from(CustomerEntity.class).where(
            (TableQuery.generateFilterCondition("PartitionKey", QueryComparisons.EQUAL, partitionKey)));
    
        // Iterate through the results
        for (CustomerEntity entity : table.execute(partitionScanQuery)) {
            System.out.println(String.format("\tCustomer: %s,%s\t%s\t%s\t%s", entity.getPartitionKey(), entity.getRowKey(), entity.getEmail(), entity.getHomePhoneNumber(), entity.  getWorkPhoneNumber()));
        }
    }
    
  • The following code shows how to delete data from the table:

    
    System.out.print("\nDelete any tables that were created.");
    
    if (table1 != null && table1.deleteIfExists() == true) {
        System.out.println(String.format("\tSuccessfully deleted the table: %s", table1.getName()));
    }
    
    if (table2 != null && table2.deleteIfExists() == true) {
        System.out.println(String.format("\tSuccessfully deleted the table: %s", table2.getName()));
    }
    

Update your connection string

Now go back to the Azure portal to get your connection string information and copy it into the app. This enables your app to communicate with your hosted database.

  1. In your Azure Cosmos DB account in the Azure portal, select Connection String.

    View the connection string information in the Connection String pane

  2. Copy the PRIMARY CONNECTION STRING using the copy button on the right.

  3. Open config.properties from the C:\git-samples\storage-table-java-getting-started\src\main\resources folder.

  4. Comment out line one and uncomment line two. The first two lines should now look like this.

    #StorageConnectionString = UseDevelopmentStorage=true
    StorageConnectionString = DefaultEndpointsProtocol=https;AccountName=[ACCOUNTNAME];AccountKey=[ACCOUNTKEY]
    
  5. Paste your PRIMARY CONNECTION STRING from the portal into the StorageConnectionString value in line 2.

    Important

    If your Endpoint uses documents.azure.com, that means you have a preview account, and you need to create a new Table API account to work with the generally available Table API SDK.

  6. Save the config.properties file.

You've now updated your app with all the info it needs to communicate with Azure Cosmos DB.

Run the app

  1. In the git terminal window, cd to the storage-table-java-getting-started folder.

    cd "C:\git-samples\storage-table-java-getting-started"
    
  2. In the git terminal window, run the following commands to run the Java application.

    mvn compile exec:java 
    

    The console window displays the table data being added to the new table database in Azure Cosmos DB.

    You can now go back to Data Explorer and see, query, modify, and work with this new data.

Review SLAs in the Azure portal

The Azure portal monitors your Cosmos DB account throughput, storage, availability, latency, and consistency. Charts for metrics associated with an Azure Cosmos DB Service Level Agreement (SLA) show the SLA value compared to actual performance. This suite of metrics makes monitoring your SLAs transparent.

To review metrics and SLAs:

  1. Select Metrics in your Cosmos DB account's navigation menu.

  2. Select a tab such as Latency, and select a timeframe on the right. Compare the Actual and SLA lines on the charts.

    Azure Cosmos DB metrics suite

  3. Review the metrics on the other tabs.

Clean up resources

When you're done with your app and Azure Cosmos DB account, you can delete the Azure resources you created so you don't incur more charges. To delete the resources:

  1. In the Azure portal Search bar, search for and select Resource groups.

  2. From the list, select the resource group you created for this quickstart.

    Select the resource group to delete

  3. On the resource group Overview page, select Delete resource group.

    Delete the resource group

  4. In the next window, enter the name of the resource group to delete, and then select Delete.

Next steps

In this quickstart, you learned how to create an Azure Cosmos DB account, create a table using the Data Explorer, and run a Java app to add table data. Now you can query your data using the Table API.