Quickstart: Azure Cosmos DB for NoSQL library for Java
APPLIES TO: NoSQL
Get started with the Azure Cosmos DB for NoSQL client library for Java to query data in your containers and perform common operations on individual items. Follow these steps to deploy a minimal solution to your environment using the Azure Developer CLI.
API reference documentation | Library source code | Package (Maven) | Azure Developer CLI
Prerequisites
- An Azure account with an active subscription. Create an account.
- GitHub account
- An Azure account with an active subscription. Create an account.
- Azure Developer CLI
- Docker Desktop
Setting up
Deploy this project's development container to your environment. Then, use the Azure Developer CLI (azd
) to create an Azure Cosmos DB for NoSQL account and deploy a containerized sample application. The sample application uses the client library to manage, create, read, and query sample data.
Important
GitHub accounts include an entitlement of storage and core hours at no cost. For more information, see included storage and core hours for GitHub accounts.
Open a terminal in the root directory of the project.
Authenticate to the Azure Developer CLI using
azd auth login
. Follow the steps specified by the tool to authenticate to the CLI using your preferred Azure credentials.azd auth login
Use
azd init
to initialize the project.azd init --template cosmos-db-nosql-java-quickstart
Note
This quickstart uses the azure-samples/cosmos-db-nosql-java-quickstart template GitHub repository. The Azure Developer CLI will automatically clone this project to your machine if it is not already there.
During initialization, configure a unique environment name.
Tip
The environment name will also be used as the target resource group name. For this quickstart, consider using
msdocs-cosmos-db
.Deploy the Azure Cosmos DB account using
azd up
. The Bicep templates also deploy a sample web application.azd up
During the provisioning process, select your subscription and desired location. Wait for the provisioning process to complete. The process can take approximately five minutes.
Once the provisioning of your Azure resources is done, a URL to the running web application is included in the output.
Deploying services (azd deploy) (✓) Done: Deploying service web - Endpoint: <https://[container-app-sub-domain].azurecontainerapps.io> SUCCESS: Your application was provisioned and deployed to Azure in 5 minutes 0 seconds.
Use the URL in the console to navigate to your web application in the browser. Observe the output of the running app.
Install the client library
The client library is available through Maven, as the azure-spring-data-cosmos
package.
Navigate to the
/src/web
folder and open the pom.xml file.If it doesn't already exist, add an entry for the
azure-spring-data-cosmos
package.<dependency> <groupId>com.azure</groupId> <artifactId>azure-spring-data-cosmos</artifactId> </dependency>
Also, add another dependency for the
azure-identity
package if it doesn't already exist.<dependency> <groupId>com.azure</groupId> <artifactId>azure-identity</artifactId> </dependency>
Object model
Name | Description |
---|---|
EnableCosmosRepositories |
This type is a method decorator used to configure a repository to access Azure Cosmos DB for NoSQL. |
CosmosRepository |
This class is the primary client class and is used to manage data within a container. |
CosmosClientBuilder |
This class is a factory used to create a client used by the repository. |
Query |
This type is a method decorator used to specify the query that the repository executes. |
Code examples
The sample code in the template uses a database named cosmicworks
and container named products
. The products
container contains details such as name, category, quantity, a unique identifier, and a sale flag for each product. The container uses the /category
property as a logical partition key.
Authenticate the client
Application requests to most Azure services must be authorized. Use the DefaultAzureCredential
type as the preferred way to implement a passwordless connection between your applications and Azure Cosmos DB for NoSQL. DefaultAzureCredential
supports multiple authentication methods and determines which method should be used at runtime.
Important
You can also authorize requests to Azure services using passwords, connection strings, or other credentials directly. However, this approach should be used with caution. Developers must be diligent to never expose these secrets in an unsecure location. Anyone who gains access to the password or secret key is able to authenticate to the database service. DefaultAzureCredential
offers improved management and security benefits over the account key to allow passwordless authentication without the risk of storing keys.
First, this sample creates a new class that inherits from AbstractCosmosConfiguration
to configure the connection to Azure Cosmos DB for NoSQL.
package com.microsoft.learn.azure.cosmosdb.nosql.quickstart;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.azure.cosmos.CosmosClientBuilder;
import com.azure.identity.DefaultAzureCredential;
import com.azure.identity.DefaultAzureCredentialBuilder;
import com.azure.spring.data.cosmos.config.AbstractCosmosConfiguration;
import com.azure.spring.data.cosmos.config.CosmosConfig;
import com.azure.spring.data.cosmos.repository.config.EnableCosmosRepositories;
// <repository_configuration>
@Configuration
@EnableCosmosRepositories
public class CosmosConfiguration extends AbstractCosmosConfiguration {
// </repository_configuration>
@Value("#{environment.COSMOS_DB_ENDPOINT}")
private String uri;
// <create_client>
@Bean
public CosmosClientBuilder getCosmosClientBuilder() {
DefaultAzureCredential azureTokenCredential = new DefaultAzureCredentialBuilder()
.build();
return new CosmosClientBuilder()
.endpoint(uri)
.credential(azureTokenCredential);
}
// </create_client>
@Override
public CosmosConfig cosmosConfig() {
return CosmosConfig.builder()
.enableQueryMetrics(true)
.build();
}
// <get_database>
@Override
protected String getDatabaseName() {
return "cosmicworks";
}
// </get_database>
}
Within the configuration class, this sample creates a new instance of the CosmosClientBuilder
class and configures authentication using a DefaultAzureCredential
instance.
package com.microsoft.learn.azure.cosmosdb.nosql.quickstart;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.azure.cosmos.CosmosClientBuilder;
import com.azure.identity.DefaultAzureCredential;
import com.azure.identity.DefaultAzureCredentialBuilder;
import com.azure.spring.data.cosmos.config.AbstractCosmosConfiguration;
import com.azure.spring.data.cosmos.config.CosmosConfig;
import com.azure.spring.data.cosmos.repository.config.EnableCosmosRepositories;
// <repository_configuration>
@Configuration
@EnableCosmosRepositories
public class CosmosConfiguration extends AbstractCosmosConfiguration {
// </repository_configuration>
@Value("#{environment.COSMOS_DB_ENDPOINT}")
private String uri;
// <create_client>
@Bean
public CosmosClientBuilder getCosmosClientBuilder() {
DefaultAzureCredential azureTokenCredential = new DefaultAzureCredentialBuilder()
.build();
return new CosmosClientBuilder()
.endpoint(uri)
.credential(azureTokenCredential);
}
// </create_client>
@Override
public CosmosConfig cosmosConfig() {
return CosmosConfig.builder()
.enableQueryMetrics(true)
.build();
}
// <get_database>
@Override
protected String getDatabaseName() {
return "cosmicworks";
}
// </get_database>
}
Get a database
In the configuration class, the sample implements a method to return the name of the existing database named cosmicworks
.
package com.microsoft.learn.azure.cosmosdb.nosql.quickstart;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.azure.cosmos.CosmosClientBuilder;
import com.azure.identity.DefaultAzureCredential;
import com.azure.identity.DefaultAzureCredentialBuilder;
import com.azure.spring.data.cosmos.config.AbstractCosmosConfiguration;
import com.azure.spring.data.cosmos.config.CosmosConfig;
import com.azure.spring.data.cosmos.repository.config.EnableCosmosRepositories;
// <repository_configuration>
@Configuration
@EnableCosmosRepositories
public class CosmosConfiguration extends AbstractCosmosConfiguration {
// </repository_configuration>
@Value("#{environment.COSMOS_DB_ENDPOINT}")
private String uri;
// <create_client>
@Bean
public CosmosClientBuilder getCosmosClientBuilder() {
DefaultAzureCredential azureTokenCredential = new DefaultAzureCredentialBuilder()
.build();
return new CosmosClientBuilder()
.endpoint(uri)
.credential(azureTokenCredential);
}
// </create_client>
@Override
public CosmosConfig cosmosConfig() {
return CosmosConfig.builder()
.enableQueryMetrics(true)
.build();
}
// <get_database>
@Override
protected String getDatabaseName() {
return "cosmicworks";
}
// </get_database>
}
Get a container
Use the Container
method decorator to configure a class to represent items in a container. Author the class to include all of the members you want to serialize into JSON. In this example, the type has a unique identifier, and fields for category, name, quantity, price, and clearance.
package com.microsoft.learn.azure.cosmosdb.nosql.quickstart;
import com.azure.spring.data.cosmos.core.mapping.Container;
import com.azure.spring.data.cosmos.core.mapping.PartitionKey;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
// <get_container>
@Container(containerName = "products", autoCreateContainer = false)
public class Item {
private String id;
private String name;
private Integer quantity;
private Boolean sale;
@PartitionKey
private String category;
// </get_container>
public Item() {
}
public Item(String id, String category, String name, Integer quantity, Boolean sale) {
this.id = id;
this.category = category;
this.name = name;
this.quantity = quantity;
this.sale = sale;
}
public String getId() {
return this.id;
}
public void setId(String id) {
this.id = id;
}
public String getCategory() {
return this.category;
}
public void setCategory(String category) {
this.category = category;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public Integer getQuantity() {
return this.quantity;
}
public void setQuantity(Integer quantity) {
this.quantity = quantity;
}
public Boolean getSale() {
return this.sale;
}
public void setSale(Boolean sale) {
this.sale = sale;
}
@Override
public String toString() {
try {
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(this);
return json;
}
catch (JsonProcessingException e) {
return String.format("[%s]\tItem:\t%s", this.id, this.name);
}
}
}
Create an item
Create an item in the container using repository.save
.
package com.microsoft.learn.azure.cosmosdb.nosql.quickstart;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.simp.SimpMessageSendingOperations;
import org.springframework.stereotype.Controller;
import com.azure.cosmos.models.PartitionKey;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
@Controller
public class StartController {
private static SimpMessageSendingOperations messageSendingOperations;
private ItemRepository repository;
@Autowired
public StartController(SimpMessageSendingOperations messageSendingOperations, ItemRepository repository) {
StartController.messageSendingOperations = messageSendingOperations;
this.repository = repository;
}
@MessageMapping("/start")
public void start() throws Exception {
this.sendMessage("Current Status:\tStarting...");
repository.deleteAll();
this.sendMessage(String.format("Get database:\t%s", "cosmicworks"));
this.sendMessage(String.format("Get container:\t%s", "products"));
{
// <create_item>
Item item = new Item(
"70b63682-b93a-4c77-aad2-65501347265f",
"gear-surf-surfboards",
"Yamba Surfboard",
12,
false
);
Item created_item = repository.save(item);
// </create_item>
this.sendMessage(String.format("Upserted item:\t%s", created_item));
}
{
Item item = new Item(
"25a68543-b90c-439d-8332-7ef41e06a0e0",
"gear-surf-surfboards",
"Kiama Classic Surfboard",
4,
true
);
Item created_item = repository.save(item);
this.sendMessage(String.format("Upserted item:\t%s", created_item));
}
// <read_item>
PartitionKey partitionKey = new PartitionKey("gear-surf-surfboards");
Optional<Item> existing_item = repository.findById("70b63682-b93a-4c77-aad2-65501347265f", partitionKey);
if (existing_item.isPresent()) {
// Do something
}
// </read_item>
existing_item.ifPresent(i -> {
this.sendMessage(String.format("Read item id:\t%s", i.getId()));
this.sendMessage(String.format("Read item:\t%s", i));
});
// <query_items>
List<Item> items = repository.getItemsByCategory("gear-surf-surfboards");
for (Item item : items) {
// Do something
}
// </query_items>
this.sendMessage("Found items:");
try {
ObjectWriter writer = new ObjectMapper().writer().withDefaultPrettyPrinter();
String json = writer.writeValueAsString(items);
this.sendMessage(json);
}
catch (JsonProcessingException e) {
this.sendMessage(String.format("Number of items:\t%s", items.size()));
}
}
private void sendMessage(String message)
{
StartController.messageSendingOperations.convertAndSend("/topic/output", new Payload(message));
}
}
Read an item
Perform a point read operation by using both the unique identifier (id
) and partition key fields. Use repository.findById
to efficiently retrieve the specific item.
package com.microsoft.learn.azure.cosmosdb.nosql.quickstart;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.simp.SimpMessageSendingOperations;
import org.springframework.stereotype.Controller;
import com.azure.cosmos.models.PartitionKey;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
@Controller
public class StartController {
private static SimpMessageSendingOperations messageSendingOperations;
private ItemRepository repository;
@Autowired
public StartController(SimpMessageSendingOperations messageSendingOperations, ItemRepository repository) {
StartController.messageSendingOperations = messageSendingOperations;
this.repository = repository;
}
@MessageMapping("/start")
public void start() throws Exception {
this.sendMessage("Current Status:\tStarting...");
repository.deleteAll();
this.sendMessage(String.format("Get database:\t%s", "cosmicworks"));
this.sendMessage(String.format("Get container:\t%s", "products"));
{
// <create_item>
Item item = new Item(
"70b63682-b93a-4c77-aad2-65501347265f",
"gear-surf-surfboards",
"Yamba Surfboard",
12,
false
);
Item created_item = repository.save(item);
// </create_item>
this.sendMessage(String.format("Upserted item:\t%s", created_item));
}
{
Item item = new Item(
"25a68543-b90c-439d-8332-7ef41e06a0e0",
"gear-surf-surfboards",
"Kiama Classic Surfboard",
4,
true
);
Item created_item = repository.save(item);
this.sendMessage(String.format("Upserted item:\t%s", created_item));
}
// <read_item>
PartitionKey partitionKey = new PartitionKey("gear-surf-surfboards");
Optional<Item> existing_item = repository.findById("70b63682-b93a-4c77-aad2-65501347265f", partitionKey);
if (existing_item.isPresent()) {
// Do something
}
// </read_item>
existing_item.ifPresent(i -> {
this.sendMessage(String.format("Read item id:\t%s", i.getId()));
this.sendMessage(String.format("Read item:\t%s", i));
});
// <query_items>
List<Item> items = repository.getItemsByCategory("gear-surf-surfboards");
for (Item item : items) {
// Do something
}
// </query_items>
this.sendMessage("Found items:");
try {
ObjectWriter writer = new ObjectMapper().writer().withDefaultPrettyPrinter();
String json = writer.writeValueAsString(items);
this.sendMessage(json);
}
catch (JsonProcessingException e) {
this.sendMessage(String.format("Number of items:\t%s", items.size()));
}
}
private void sendMessage(String message)
{
StartController.messageSendingOperations.convertAndSend("/topic/output", new Payload(message));
}
}
Query items
Perform a query over multiple items in a container by defining a query in the repository's interface. This sample uses the Query
method decorator to define a method that executes this parameterized query:
SELECT * FROM products p WHERE p.category = @category
package com.microsoft.learn.azure.cosmosdb.nosql.quickstart;
import java.util.List;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import com.azure.spring.data.cosmos.repository.CosmosRepository;
import com.azure.spring.data.cosmos.repository.Query;
// <repository_implementation>
@Repository
public interface ItemRepository extends CosmosRepository<Item, String> {
@Query("SELECT * FROM products p WHERE p.category = @category")
List<Item> getItemsByCategory(@Param("category") String category);
}
// </repository_implementation>
Fetch all of the results of the query using repository.getItemsByCategory
. Loop through the results of the query.
package com.microsoft.learn.azure.cosmosdb.nosql.quickstart;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.simp.SimpMessageSendingOperations;
import org.springframework.stereotype.Controller;
import com.azure.cosmos.models.PartitionKey;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
@Controller
public class StartController {
private static SimpMessageSendingOperations messageSendingOperations;
private ItemRepository repository;
@Autowired
public StartController(SimpMessageSendingOperations messageSendingOperations, ItemRepository repository) {
StartController.messageSendingOperations = messageSendingOperations;
this.repository = repository;
}
@MessageMapping("/start")
public void start() throws Exception {
this.sendMessage("Current Status:\tStarting...");
repository.deleteAll();
this.sendMessage(String.format("Get database:\t%s", "cosmicworks"));
this.sendMessage(String.format("Get container:\t%s", "products"));
{
// <create_item>
Item item = new Item(
"70b63682-b93a-4c77-aad2-65501347265f",
"gear-surf-surfboards",
"Yamba Surfboard",
12,
false
);
Item created_item = repository.save(item);
// </create_item>
this.sendMessage(String.format("Upserted item:\t%s", created_item));
}
{
Item item = new Item(
"25a68543-b90c-439d-8332-7ef41e06a0e0",
"gear-surf-surfboards",
"Kiama Classic Surfboard",
4,
true
);
Item created_item = repository.save(item);
this.sendMessage(String.format("Upserted item:\t%s", created_item));
}
// <read_item>
PartitionKey partitionKey = new PartitionKey("gear-surf-surfboards");
Optional<Item> existing_item = repository.findById("70b63682-b93a-4c77-aad2-65501347265f", partitionKey);
if (existing_item.isPresent()) {
// Do something
}
// </read_item>
existing_item.ifPresent(i -> {
this.sendMessage(String.format("Read item id:\t%s", i.getId()));
this.sendMessage(String.format("Read item:\t%s", i));
});
// <query_items>
List<Item> items = repository.getItemsByCategory("gear-surf-surfboards");
for (Item item : items) {
// Do something
}
// </query_items>
this.sendMessage("Found items:");
try {
ObjectWriter writer = new ObjectMapper().writer().withDefaultPrettyPrinter();
String json = writer.writeValueAsString(items);
this.sendMessage(json);
}
catch (JsonProcessingException e) {
this.sendMessage(String.format("Number of items:\t%s", items.size()));
}
}
private void sendMessage(String message)
{
StartController.messageSendingOperations.convertAndSend("/topic/output", new Payload(message));
}
}