Java – Connect to Azure Cosmos DB (SQL API) No.11

In this blog, how to connect to Cosmos DB SQL API by Java is shown.

▼1. Connect to Azure Cosmos DB

Azure Cosmos DB is NoSQL Database. it is not Relational Database. we don’t need to set schema and table beforehand. we need to set partition key for a collection of a container to distribute data into the partitions.


▼2. Prerequisites

2-1. Prepare for a trial free Azure Cosmos DB Account, not necessary for a subscription

https://cosmos.azure.com/try/

2-2. Enable Maven auto-import in IntelliJ IDEA

Enable auto-import on IntelliJ IDEA No.13

2-3. Update Pom.xml

Please change the latest version each libraries.

(a part of pom.xml)

<dependencies>
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-simple</artifactId>
        <version>1.7.30</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/com.azure/azure-cosmos -->
    <dependency>
        <groupId>com.azure</groupId>
        <artifactId>azure-cosmos</artifactId>
        <version>4.1.0</version>
    </dependency>
    <dependency>
        <groupId>io.netty</groupId>
        <artifactId>netty-tcnative</artifactId>
        <version>2.0.31.Final</version>
        <classifier>linux-x86_64</classifier>
    </dependency>
</dependencies>

▼3. Connect to Cosmos DB by Java

3-1. Develop a Java code for the connection to Azure Cosmos DB

Update parameters of both end_point  and master_key according to your Azure Cosmos DB Account information from the portal site.

import com.azure.cosmos.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Collections;

public class conCosmosDBv3 {
    protected static final Logger log = LoggerFactory.getLogger(conCosmosDBv3.class);
    public static void main(String[] args) {
        String databaseName = "testcosmosdb";
        String end_point = "https://xxxx.documents.azure.com:443";
        String master_key = "xxxx";
        try (CosmosClient cosmosClient = new CosmosClientBuilder().endpoint(end_point).key(master_key).directMode(DirectConnectionConfig.getDefaultConfig()).consistencyLevel(ConsistencyLevel.SESSION).connectionSharingAcrossClientsEnabled(true).contentResponseOnWriteEnabled(true).userAgentSuffix("My-Application-clienttest").preferredRegions(Collections.singletonList("West US")).buildClient()){
            log.info("The connection to Cosmos DB succeeded.");
        }catch(CosmosException e){
            e.printStackTrace();
        }
    }
}

3-2. Results of running this code.

[main] INFO com.azure.cosmos.implementation.RxDocumentClientImpl - Initializing DocumentClient with serviceEndpoint [https://xxx.documents.azure.com:443], connectionPolicy [ConnectionPolicy{requestTimeout=PT5S, connectionMode=DIRECT, maxConnectionPoolSize=1000, idleConnectionTimeout=PT0S, userAgentSuffix='My-Application-clienttest', throttlingRetryOptions=RetryOptions{maxRetryAttemptsOnThrottledRequests=9, maxRetryWaitTime=PT30S}, endpointDiscoveryEnabled=true, preferredRegions=[West US], multipleWriteRegionsEnabled=true, proxyType=null, inetSocketProxyAddress=null, readRequestsFallbackEnabled=true, connectTimeout=PT1M, idleEndpointTimeout=PT1M10S, maxConnectionsPerEndpoint=130, maxRequestsPerConnection=30}], consistencyLevel [Session], directModeProtocol [Tcp]
[main] INFO com.azure.cosmos.implementation.http.SharedGatewayHttpClient - creating a new shared HttpClient
[parallel-1] INFO com.azure.cosmos.implementation.RxDocumentClientImpl - Getting database account endpoint from https://xxx.documents.azure.com:443
[main] INFO com.azure.cosmos.implementation.directconnectivity.SharedTransportClient - creating a new shared RntbdTransportClient
[main] INFO conCosmosDBv3 - The connection to Cosmos DB succeeded.
[main] INFO com.azure.cosmos.implementation.RxDocumentClientImpl - Shutting down ...
[main] INFO com.azure.cosmos.implementation.RxDocumentClientImpl - Closing Global Endpoint Manager ...
[main] INFO com.azure.cosmos.implementation.RxDocumentClientImpl - Closing StoreClientFactory ...
[main] INFO com.azure.cosmos.implementation.directconnectivity.SharedTransportClient - closing one reference to the shared RntbdTransportClient, the number of remaining references is 0
[main] INFO com.azure.cosmos.implementation.directconnectivity.SharedTransportClient - All references to shared RntbdTransportClient are closed. Closing the underlying RntbdTransportClient
[main] INFO com.azure.cosmos.implementation.RxDocumentClientImpl - Shutting down reactorHttpClient ...
[main] INFO com.azure.cosmos.implementation.http.SharedGatewayHttpClient - closing one reference to the shared HttpClient, the number of remaining references is 0
[main] INFO com.azure.cosmos.implementation.http.SharedGatewayHttpClient - All references to shared HttpClient are closed. Closing the underlying HttpClient
[main] INFO com.azure.cosmos.implementation.RxDocumentClientImpl - Shutting down completed.

▼4. Preference

  1. Try Azure Cosmos DB for free  https://docs.microsoft.com/en-us/azure/cosmos-db/optimize-dev-test#try-azure-cosmos-db-for-free
  2. Understanding the differences between NoSQL and relational databases https://docs.microsoft.com/en-us/azure/cosmos-db/relational-nosql
  3. Azure Cosmos DB Java SDK v4 for Core (SQL) API: release notes and resources https://docs.microsoft.com/en-us/azure/cosmos-db/sql-api-sdk-java-v4
  4. How do I disable or enable Gradle / Maven auto-import for an IntelliJ IDEA project? https://stackoverflow.com/questions/43192504/how-do-i-disable-or-enable-gradle-maven-auto-import-for-an-intellij-idea-proje
  5. Microsoft Azure Cosmos DB Sync Java SDK https://github.com/Azure/azure-documentdb-java

That’s all. Have a nice day ahead !!!

Leave a Reply

Your email address will not be published. Required fields are marked *