title | description | author | ms.service | ms.subservice | ms.devlang | ms.topic | ms.date | ms.author | ms.custom |
---|---|---|---|---|---|---|---|---|---|
Use the Table API and Java to build an app - Azure Cosmos DB |
This quickstart shows how to use the Azure Cosmos DB Table API to create an application with the Azure portal and Java |
SnehaGunda |
cosmos-db |
cosmosdb-table |
java |
quickstart |
05/28/2020 |
sngun |
seo-java-august2019, seo-java-september2019, devx-track-java |
[!div class="op_single_selector"]
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.
- An Azure account with an active subscription. Create one for free. Or try Azure Cosmos DB for free without an Azure subscription. You can also use the Azure Cosmos DB Emulator with a URI of
https://localhost:8081
and the keyC2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw==
. - Java Development Kit (JDK) 8. Point your
JAVA_HOME
environment variable to the folder where the JDK is installed. - A Maven binary archive.
- Git.
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.
[!INCLUDE cosmos-db-create-dbaccount-table]
[!INCLUDE cosmos-db-create-table]
[!INCLUDE cosmos-db-create-table-add-sample-data]
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.
-
Open a command prompt, create a new folder named git-samples, then close the command prompt.
md "C:\git-samples"
-
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"
-
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.
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())); }
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.
-
In your Azure Cosmos DB account in the Azure portal, select Connection String.
:::image type="content" source="./media/create-table-java/cosmos-db-quickstart-connection-string.png" alt-text="View the connection string information in the Connection String pane":::
-
Copy the PRIMARY CONNECTION STRING using the copy button on the right.
-
Open config.properties from the C:\git-samples\storage-table-java-getting-started\src\main\resources folder.
-
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]
-
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.
-
Save the config.properties file.
You've now updated your app with all the info it needs to communicate with Azure Cosmos DB.
-
In the git terminal window,
cd
to the storage-table-java-getting-started folder.cd "C:\git-samples\storage-table-java-getting-started"
-
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.
[!INCLUDE cosmosdb-tutorial-review-slas]
[!INCLUDE cosmosdb-delete-resource-group]
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.
[!div class="nextstepaction"] Import table data to the Table API