Skip navigation links

Azure SDK for Java Reference Documentation

Current version is 3.0.0-beta.1, click here for the index

See: Description

Other Packages 
Package Description
com.azure.spring.data.cosmos
Cosmosdb class for spring
com.azure.spring.data.cosmos.common
This package contains the classes of utils for cosmosdb
com.azure.spring.data.cosmos.config
This package contains the classes to configure properties of cosmos db
com.azure.spring.data.cosmos.core
This package contains the core classes of cosmos db, includes converters, query generators and mapping to cosmos entities
com.azure.spring.data.cosmos.core.convert
This package contains the converter classes of cosmos db
com.azure.spring.data.cosmos.core.generator
This package contains the generator classes of cosmos db
com.azure.spring.data.cosmos.core.mapping
This package contains the mapping classes of cosmos persistent entities
com.azure.spring.data.cosmos.core.query
This package contains the query classes of cosmos db document
com.azure.spring.data.cosmos.exception
This package contains the exception classes of cosmos db
com.azure.spring.data.cosmos.repository
This package contains the support, query and config classes of setting up cosmosdb repositories
com.azure.spring.data.cosmos.repository.config
This package contains the config classes of setting up cosmosdb repositories
com.azure.spring.data.cosmos.repository.query
This package contains the process cosmos queries
com.azure.spring.data.cosmos.repository.support
This package contains the support classes of setting up cosmosdb repositories and factories
Current version is 3.0.0-beta.1, click here for the index

Azure Spring Data Cosmos Core client library for Java

Azure Spring Data Cosmos provides core Spring Data support for Azure Cosmos DB using the SQL API, based on Spring Data framework. Azure Cosmos DB is a globally-distributed database service which allows developers to work with data using a variety of standard APIs, such as SQL, MongoDB, Cassandra, Graph, and Table.

Spring data version support

This project supports both spring-data-commons 2.2.x and spring-data-commons 2.3.x versions.

Getting started

Include the package

Please refer to azure-spring-data-2-2-cosmos readme or azure-spring-data-2-3-cosmos readme on how to include the individual packages.

Prerequisites

SLF4J is only needed if you plan to use logging, please also download an SLF4J binding which will link the SLF4J API with the logging implementation of your choice. See the SLF4J user manual for more information.

Setup Configuration Class

 @Configuration
 @EnableCosmosRepositories
public class AppConfiguration extends AbstractCosmosConfiguration {

    private static final Logger logger = LoggerFactory.getLogger(AppConfiguration.class);

     @Value("${azure.cosmos.uri}")
    private String uri;

     @Value("${azure.cosmos.key}")
    private String key;

     @Value("${azure.cosmos.secondaryKey}")
    private String secondaryKey;

     @Value("${azure.cosmos.database}")
    private String dbName;

     @Value("${azure.cosmos.queryMetricsEnabled}")
    private boolean queryMetricsEnabled;

    private AzureKeyCredential azureKeyCredential;

     @Bean
    public CosmosClientBuilder getCosmosClientBuilder() {
        this.azureKeyCredential = new AzureKeyCredential(key);
        DirectConnectionConfig directConnectionConfig = new DirectConnectionConfig();
        GatewayConnectionConfig gatewayConnectionConfig = new GatewayConnectionConfig();
        return new CosmosClientBuilder()
            .endpoint(uri)
            .credential(azureKeyCredential)
            .directMode(directConnectionConfig, gatewayConnectionConfig);
    }

     @Override
    public CosmosConfig cosmosConfig() {
        return CosmosConfig.builder()
                           .enableQueryMetrics(queryMetricsEnabled)
                           .responseDiagnosticsProcessor(new ResponseDiagnosticsProcessorImplementation())
                           .build();
    }

    public void switchToSecondaryKey() {
        this.azureKeyCredential.update(secondaryKey);
    }

     @Override
    protected String getDatabaseName() {
        return "testdb";
    }

    private static class ResponseDiagnosticsProcessorImplementation implements ResponseDiagnosticsProcessor {

         @Override
        public void processResponseDiagnostics( @Nullable ResponseDiagnostics responseDiagnostics) {
            logger.info("Response Diagnostics {}", responseDiagnostics);
        }
    }

}

Customizing Configuration

You can customize DirectConnectionConfig or GatewayConnectionConfig or both and provide them to CosmosClientBuilder bean to customize CosmosAsyncClient

 @Bean
public CosmosClientBuilder getCosmosClientBuilder() {

    DirectConnectionConfig directConnectionConfig = new DirectConnectionConfig();
    GatewayConnectionConfig gatewayConnectionConfig = new GatewayConnectionConfig();
    return new CosmosClientBuilder()
        .endpoint(uri)
        .directMode(directConnectionConfig, gatewayConnectionConfig);
}

 @Override
public CosmosConfig cosmosConfig() {
    return CosmosConfig.builder()
                       .enableQueryMetrics(queryMetricsEnabled)
                       .responseDiagnosticsProcessor(new ResponseDiagnosticsProcessorImplementation())
                       .build();
}

By default, @EnableCosmosRepositories will scan the current package for any interfaces that extend one of Spring Data's repository interfaces. Use it to annotate your Configuration class to scan a different root package by @EnableCosmosRepositories(basePackageClass=UserRepository.class) if your project layout has multiple projects.

Define an entity

 @Container(containerName = "myContainer", ru = "400")
public class User {
    private String id;
    private String firstName;


     @PartitionKey
    private String lastName;

    public User() {
        // If you do not want to create a default constructor,
        // use annotation  @JsonCreator and  @JsonProperty in the full args constructor
    }

    public User(String id, String firstName, String lastName) {
        this.id = id;
        this.firstName = firstName;
        this.lastName = lastName;
    }

     @Override
    public String toString() {
        return String.format("User: %s %s, %s", firstName, lastName, id);
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
}
 @Container(containerName = "myContainer")
public class UserSample {
     @Id
    private String emailAddress;

}

Create repositories

Extends CosmosRepository interface, which provides Spring Data repository support.

 @Repository
public interface UserRepository extends CosmosRepository<User, String> {
    Iterable<User> findByFirstName(String firstName);
    User findOne(String id, String lastName);
}

Create an Application class

Here create an application class with all the components

 @SpringBootApplication
public class SampleApplication implements CommandLineRunner {

     @Autowired
    private UserRepository repository;

     @Autowired
    private ApplicationContext applicationContext;

    public static void main(String[] args) {
        SpringApplication.run(SampleApplication.class, args);
    }

    public void run(String... var1) {

        final User testUser = new User("testId", "testFirstName", "testLastName");

        repository.deleteAll();
        repository.save(testUser);

        // to find by Id, please specify partition key value if collection is partitioned
        final User result = repository.findOne(testUser.getId(), testUser.getLastName());

        //  Switch to secondary key
        UserRepositoryConfiguration bean =
            applicationContext.getBean(UserRepositoryConfiguration.class);
        bean.switchToSecondaryKey();

        //  Now repository will use secondary key
        repository.save(testUser);

    }
}

Key concepts

CrudRepository and ReactiveCrudRepository

Spring Data Annotations

// Indicate if indexing policy use automatic or not
// Default value is true
boolean automatic() default Constants.DEFAULT_INDEXING_POLICY_AUTOMATIC;

// Indexing policy mode, option Consistent.
IndexingMode mode() default IndexingMode.CONSISTENT;

// Included paths for indexing
String[] includePaths() default {};

// Excluded paths for indexing
String[] excludePaths() default {};

Azure Cosmos DB Partition

Optimistic Locking

 @Container(containerName = "myContainer")
public class MyItem {
    String id;
    String data;
     @Version
    String _etag;
}

Spring Data custom query, pageable and sorting

private List<T> findAllWithPageSize(int pageSize) {

    final CosmosPageRequest pageRequest = new CosmosPageRequest(0, pageSize, null);
    Page<T> page = repository.findAll(pageRequest);
    List<T> pageContent = page.getContent();
    while (page.hasNext()) {
        Pageable nextPageable = page.nextPageable();
        page = repository.findAll(nextPageable);
        pageContent = page.getContent();
    }
    return pageContent;
}

Spring Boot Starter Data Rest

 @Bean(name = "cosmosObjectMapper")
public ObjectMapper objectMapper() {
    return new ObjectMapper(); // Do configuration to the ObjectMapper if required
}

Auditing

 @Container(containerName = "myContainer")
public class AuditableUser {
    private String id;
    private String firstName;
     @CreatedBy
    private String createdBy;
     @CreatedDate
    private OffsetDateTime createdDate;
     @LastModifiedBy
    private String lastModifiedBy;
     @LastModifiedDate
    private OffsetDateTime lastModifiedByDate;
}

Multi-database configuration

The example uses the application.properties file

# primary account cosmos config
azure.cosmos.primary.uri=your-primary-cosmosDb-uri
azure.cosmos.primary.key=your-primary-cosmosDb-key
azure.cosmos.primary.secondaryKey=your-primary-cosmosDb-secondary-key
azure.cosmos.primary.database=your-primary-cosmosDb-dbName
azure.cosmos.primary.populateQueryMetrics=if-populate-query-metrics

# secondary account cosmos config
azure.cosmos.secondary.uri=your-secondary-cosmosDb-uri
azure.cosmos.secondary.key=your-secondary-cosmosDb-key
azure.cosmos.secondary.secondaryKey=your-secondary-cosmosDb-secondary-key
azure.cosmos.secondary.database=your-secondary-cosmosDb-dbName
azure.cosmos.secondary.populateQueryMetrics=if-populate-query-metrics
 @Configuration
 @EnableCosmosAuditing
 @PropertySource("classpath:application.properties")
public class DatabaseConfiguration extends AbstractCosmosConfiguration {

    private static final Logger LOGGER = LoggerFactory.getLogger(DatabaseConfiguration.class);

     @Bean
     @ConfigurationProperties(prefix = "azure.cosmos.primary")
    public CosmosProperties primaryDataSourceConfiguration() {
        return new CosmosProperties();
    }

     @Bean
     @ConfigurationProperties(prefix = "azure.cosmos.secondary")
    public CosmosProperties secondaryDataSourceConfiguration() {
        return new CosmosProperties();
    }

     @Autowired
     @Qualifier("primaryDataSourceConfiguration")
    CosmosProperties primaryProperties;

     @Autowired
     @Qualifier("secondaryDataSourceConfiguration")
    CosmosProperties secondaryProperties;

     @Autowired(required = false)
    private IsNewAwareAuditingHandler cosmosAuditingHandler;

     @Bean
    public CosmosClientBuilder cosmosClientBuilder() {
        return new CosmosClientBuilder()
            .key(primaryProperties.getKey())
            .endpoint(primaryProperties.getUri());
    }

     @Bean
    public CosmosClientBuilder secondaryCosmosClientBuilder() {
        return new CosmosClientBuilder()
            .key(secondaryProperties.getKey())
            .endpoint(secondaryProperties.getUri());
    }
    // -------------------------First Cosmos Client for First Cosmos Account---------------------------
     @EnableReactiveCosmosRepositories(basePackages = "com.azure.cosmos.multidatasource.primarydatasource.first")
    public class PrimaryDataSourceConfiguration {

    }
     @EnableReactiveCosmosRepositories(basePackages = "com.azure.cosmos.multidatasource.primarydatasource.second", reactiveCosmosTemplateRef = "primaryReactiveCosmosTemplate")
    public class PrimaryDataSourceConfiguration2 {
         @Bean
        public ReactiveCosmosTemplate primaryReactiveCosmosTemplate(CosmosAsyncClient cosmosAsyncClient, CosmosConfig cosmosConfig, MappingCosmosConverter mappingCosmosConverter) {
            return new ReactiveCosmosTemplate(cosmosAsyncClient, "test1_2", cosmosConfig, mappingCosmosConverter, cosmosAuditingHandler);
        }
    }

    // -------------------------Second Cosmos Client for Secondary Cosmos Account---------------------------
     @Bean("secondaryCosmosAsyncClient")
    public CosmosAsyncClient getCosmosAsyncClient(CosmosClientBuilder secondaryCosmosClientBuilder) {
        return CosmosFactory.createCosmosAsyncClient(secondaryCosmosClientBuilder);
    }

     @Bean("secondaryCosmosConfig")
    public CosmosConfig getCosmosConfig() {
        return CosmosConfig.builder()
                           .enableQueryMetrics(true)
                           .responseDiagnosticsProcessor(new ResponseDiagnosticsProcessorImplementation())
                           .build();
    }

     @EnableReactiveCosmosRepositories(basePackages = "com.azure.cosmos.multidatasource.secondarydatasource.first", reactiveCosmosTemplateRef = "secondaryReactiveCosmosTemplate")
    public class SecondaryDataSourceConfiguration {
         @Bean
        public CosmosTemplate secondaryReactiveCosmosTemplate( @Qualifier("secondaryCosmosAsyncClient") CosmosAsyncClient client,  @Qualifier("secondaryCosmosConfig") CosmosConfig cosmosConfig, MappingCosmosConverter mappingCosmosConverter) {
            return new CosmosTemplate(client, "test2_1", cosmosConfig, mappingCosmosConverter, cosmosAuditingHandler);
        }
    }
     @EnableReactiveCosmosRepositories(basePackages = "com.azure.cosmos.multidatasource.secondarydatasource.second", reactiveCosmosTemplateRef = "secondaryReactiveCosmosTemplate1")
    public class SecondaryDataSourceConfiguration1 {
         @Bean
        public CosmosTemplate secondaryReactiveCosmosTemplate1( @Qualifier("secondaryCosmosAsyncClient") CosmosAsyncClient client,  @Qualifier("secondaryCosmosConfig") CosmosConfig cosmosConfig, MappingCosmosConverter mappingCosmosConverter) {
            return new CosmosTemplate(client, "test2_2", cosmosConfig, mappingCosmosConverter, cosmosAuditingHandler);
        }
    }

    private static class ResponseDiagnosticsProcessorImplementation implements ResponseDiagnosticsProcessor {

         @Override
        public void processResponseDiagnostics( @Nullable ResponseDiagnostics responseDiagnostics) {
            LOGGER.info("Response Diagnostics {}", responseDiagnostics);
        }
    }

     @Override
    protected String getDatabaseName() {
        return "test1_1";
    }
}

 @Bean("secondaryCosmosAsyncClient")
public CosmosAsyncClient getCosmosAsyncClient(CosmosClientBuilder secondaryCosmosClientBuilder) {
    return CosmosFactory.createCosmosAsyncClient(secondaryCosmosClientBuilder);
}

 @Bean("secondaryCosmosConfig")
public CosmosConfig getCosmosConfig() {
    return CosmosConfig.builder()
                       .enableQueryMetrics(true)
                       .responseDiagnosticsProcessor(new ResponseDiagnosticsProcessorImplementation())
                       .build();
}

 @SpringBootApplication
public class MultiDatasourceApplication implements CommandLineRunner {

     @Autowired
    private UserRepository userRepository;

     @Autowired
    private BookRepository bookRepository;


    private final User user = new User("1024", "1024 @geek.com", "1k", "Mars");
    private final Book book = new Book("9780792745488", "Zen and the Art of Motorcycle Maintenance", "Robert M. Pirsig");


    public static void main(String[] args) {
        SpringApplication.run(MultiDatasourceApplication.class, args);
    }

     @Override
    public void run(String... args) {
        final List<User> users = this.userRepository.findByEmailOrName(this.user.getEmail(), this.user.getName()).collectList().block();
        users.forEach(System.out::println);
        final Book book = this.bookRepository.findById("9780792745488").block();
        System.out.println(book);
    }

     @PostConstruct
    public void setup() {
        this.userRepository.save(user).block();
        this.bookRepository.save(book).block();

    }

     @PreDestroy
    public void cleanup() {
        this.userRepository.deleteAll().block();
        this.bookRepository.deleteAll().block();
    }
}

Beta version package

Beta version built from master branch are available, you can refer to the instruction to use beta version packages.

Troubleshooting

General

If you encounter any bug, please file an issue here.

To suggest a new feature or changes that could be made, file an issue the same way you would for a bug.

Enable Client Logging

<configuration>
  <include resource="/org/springframework/boot/logging/logback/base.xml"/>
  <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
    <encoder>
      <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
      </pattern>
    </encoder>
  </appender>
  <root level="info">
    <appender-ref ref="STDOUT"/>
  </root>
  <logger name="com.azure.cosmos" level="error"/>
  <logger name="org.springframework" level="error"/>
  <logger name="io.netty" level="error"/>
</configuration>

Examples

Next steps

Contributing

This project welcomes contributions and suggestions. Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us the rights to use your contribution.

When you submit a pull request, a CLA-bot will automatically determine whether you need to provide a CLA and decorate the PR appropriately (e.g., label, comment). Simply follow the instructions provided by the bot. You will only need to do this once across all repos using our CLA.

This project has adopted the Microsoft Open Source Code of Conduct. For more information see the Code of Conduct FAQ or contact opencode@microsoft.com with any additional questions or comments.

Impressions

Skip navigation links
Visit the Azure for Java Developerssite for more Java documentation, including quick starts, tutorials, and code samples.

Copyright © 2020 Microsoft Corporation. All rights reserved.