2018-04-13 10:49:05 +03:00
[![Travis CI ](https://travis-ci.org/Microsoft/spring-data-cosmosdb.svg?branch=master )](https://travis-ci.org/Microsoft/spring-data-cosmosdb)
[![codecov ](https://codecov.io/gh/Microsoft/spring-data-cosmosdb/branch/master/graph/badge.svg )](https://codecov.io/gh/Microsoft/spring-data-cosmosdb)
2018-04-13 04:30:25 +03:00
[![MIT License ](http://img.shields.io/badge/license-MIT-green.svg ) ](https://github.com/Microsoft/spring-data-cosmosdb/blob/master/LICENSE)
2017-09-19 08:02:09 +03:00
2018-04-12 07:57:10 +03:00
# Spring Data for Azure Cosmos DB
2018-01-22 09:49:10 +03:00
2018-04-12 07:57:10 +03:00
[Azure Cosmos DB ](https://docs.microsoft.com/en-us/azure/cosmos-db/introduction ) is a globally-distributed database service that allows developers to work with data using a variety of standard APIs, such as SQL, MongoDB, Cassandra, Graph, and Table.
2018-01-22 09:49:10 +03:00
2018-04-13 10:23:40 +03:00
**Spring Data Azure Cosmos DB** provides initial Spring Data support for Azure Cosmos DB using the [SQL API ](https://docs.microsoft.com/en-us/azure/cosmos-db/sql-api-introduction ), based on Spring Data framework. Currently it only supports SQL API, the other APIs are in the plan.
2017-09-18 05:45:55 +03:00
2017-09-28 11:13:33 +03:00
## TOC
2018-04-13 05:21:47 +03:00
* [Sample Code ](#sample-code )
2018-03-05 10:33:07 +03:00
* [Spring data version support ](#spring-data-version-support )
2017-09-28 11:13:33 +03:00
* [Feature List ](#feature-list )
* [Quick Start ](#quick-start )
2018-03-01 11:01:01 +03:00
* [Query Partitioned Collection ](QueryPartitionedCollection.md )
2019-03-12 10:51:48 +03:00
* [Snapshots ](#snapshots )
2017-09-28 11:13:33 +03:00
* [Filing Issues ](#filing-issues )
* [How to Contribute ](#how-to-contribute )
* [Code of Conduct ](#code-of-conduct )
2017-09-18 09:54:30 +03:00
## Sample Code
Please refer to [sample project here ](./samplecode ).
2017-09-18 05:45:55 +03:00
2018-03-05 10:33:07 +03:00
## Spring data version support
2020-02-08 05:15:22 +03:00
This repository supports both Spring Data 1.x, 2.0.x, 2.1.x and 2.2.x. Below packages are available with latest release version.
We recommend users to leverage latest version for bug fix and new features.
Name | Version for Spring Boot 2.2.x | Version for Spring Boot 2.1.x | Version for Spring Boot 2.0.x
:---:|:---:|:---:|:---:|
spring-data-cosmosdb | [![Maven Central][Branch master Badge]][Branch master Link] | [![Maven Central][Branch 2.1.x Badge]][Branch 2.1.x Link] | [![Maven Central][Branch 2.0.x Badge]][Branch 2.0.x Link]
2018-03-05 10:33:07 +03:00
2017-09-18 09:54:30 +03:00
## Feature List
2019-09-27 10:27:39 +03:00
- Spring Data ReactiveCrudRepository CrudRepository basic CRUD functionality
2017-09-18 09:54:30 +03:00
- save
- findAll
- findOne by Id
- deleteAll
- delete by Id
- delete entity
- Spring Data [@Id ](https://github.com/spring-projects/spring-data-commons/blob/db62390de90c93a78743c97cc2cc9ccd964994a5/src/main/java/org/springframework/data/annotation/Id.java ) annotation.
2017-09-19 06:33:20 +03:00
There're 2 ways to map a field in domain class to `id` field of Azure Cosmos DB document.
2017-09-18 09:54:30 +03:00
- annotate a field in domain class with `@Id` , this field will be mapped to document `id` in Cosmos DB.
2018-04-12 07:57:10 +03:00
- set name of this field to `id` , this field will be mapped to document `id` in Azure Cosmos DB.
2017-09-18 09:54:30 +03:00
- Custom collection Name.
2020-02-26 00:16:37 +03:00
By default, collection name will be class name of user domain class. To customize it, add the `@Document(collection="myCustomCollectionName")` annotation to the domain class. The collection field also supports SpEL expressions (eg. `collection = "${dynamic.collection.name}"` or `collection = "#{@someBean.getContainerName()}"` ) in order to provide collection names programmatically/via configuration properties.
2018-03-14 05:29:14 +03:00
- Custom IndexingPolicy
By default, IndexingPolicy will be set by azure service. To customize it add annotation `@DocumentIndexingPolicy` to domain class. This annotation has 4 attributes to customize, see following:
```java
boolean automatic; // Indicate if indexing policy use automatic or not
IndexingMode mode; // Indexing policy mode, option Consistent|Lazy|None.
String[] includePaths; // Included paths for indexing
String[] excludePaths; // Excluded paths for indexing
```
2019-10-02 17:41:44 +03:00
- Supports Optimistic Locking for specific collections, which means upserts/deletes by document will fail with an exception in case the document was modified by another process in the meanwhile. To enable Optimistic Locking for a collection, just create a string `_etag` field and mark it with the `@Version` annotation. See the following:
```java
@Document (collection = "myCollection")
class MyDocument {
String id;
String data;
@Version
String _etag;
}
```
2019-01-17 05:05:53 +03:00
- Supports [Azure Cosmos DB partition ](https://docs.microsoft.com/en-us/azure/cosmos-db/partition-data ). To specify a field of domain class to be partition key field, just annotate it with `@PartitionKey` . When you do CRUD operation, pls specify your partition value. For more sample on partition CRUD, pls refer to [test here ](./src/test/java/com/microsoft/azure/spring/data/cosmosdb/repository/integration/AddressRepositoryIT.java )
2018-06-04 08:13:29 +03:00
- Supports [Spring Data custom query ](https://docs.spring.io/spring-data/commons/docs/current/reference/html/#repositories.query-methods.details ) find operation, e.g., `findByAFieldAndBField`
2018-09-13 04:39:46 +03:00
- Supports [Spring Data pagable and sort ](https://docs.spring.io/spring-data/commons/docs/current/reference/html/#repositories.special-parameters ).
2019-11-07 20:53:23 +03:00
- Based on available RUs on the database account, cosmosDB can return documents less than or equal to the requested size.
- Due to this variable number of returned documents in every iteration, user should not rely on the totalPageSize, and instead iterating over pageable should be done in this way.
```java
final CosmosPageRequest pageRequest = new CosmosPageRequest(0, pageSize, null);
Page< T > page = tRepository.findAll(pageRequest);
List< T > pageContent = page.getContent();
while(page.hasNext()) {
Pageable nextPageable = page.nextPageable();
page = repository.findAll(nextPageable);
pageContent = page.getContent();
}
```
2017-12-25 06:38:28 +03:00
- Supports [spring-boot-starter-data-rest ](https://projects.spring.io/spring-data-rest/ ).
2018-01-22 12:30:45 +03:00
- Supports List and nested type in domain class.
2018-06-04 08:13:29 +03:00
- Configurable ObjectMapper bean with unique name `cosmosdbObjectMapper` , only configure customized ObjectMapper if you really need to. e.g.,
```java
@Bean (name = "cosmosdbObjectMapper")
public ObjectMapper objectMapper() {
return new ObjectMapper(); // Do configuration to the ObjectMapper if required
}
```
2019-07-27 16:45:43 +03:00
2017-09-18 09:54:30 +03:00
## Quick Start
2017-09-18 05:45:55 +03:00
2017-09-18 09:54:30 +03:00
### Add the dependency
2018-04-13 04:30:25 +03:00
`spring-data-cosmosdb` is published on Maven Central Repository.
2017-09-18 09:54:30 +03:00
If you are using Maven, add the following dependency.
2017-09-18 05:45:55 +03:00
2017-09-18 09:54:30 +03:00
```xml
< dependency >
< groupId > com.microsoft.azure< / groupId >
2018-04-13 04:30:25 +03:00
< artifactId > spring-data-cosmosdb< / artifactId >
2020-03-26 02:02:10 +03:00
< version > 2.2.3.FIX1< / version >
2017-09-18 09:54:30 +03:00
< / dependency >
```
### Setup Configuration
2018-01-22 12:30:45 +03:00
Setup configuration class.
2017-09-18 09:54:30 +03:00
2019-08-16 07:06:15 +03:00
CosmosKeyCredential feature provides capability to rotate keys on the fly. You can switch keys using switchToSecondaryKey().
For more information on this, see the Sample Application code.
2019-09-27 10:27:39 +03:00
### Sync and Reactive Repository support
2.2.x supports both sync and reactive repository support.
Use `@EnableCosmosRepositories` to enable sync repository support.
For reactive repository support, use `@EnableReactiveCosmosRepositories`
2019-10-21 17:35:53 +03:00
### Response Diagnostics String and Query Metrics
2.2.x supports Response Diagnostics String and Query Metrics.
Set `populateQueryMetrics` flag to true in application.properties to enable query metrics.
In addition to setting the flag, implement `ResponseDiagnosticsProcessor` to log diagnostics information.
2018-08-23 05:16:35 +03:00
```java
2017-09-18 09:54:30 +03:00
@Configuration
2019-09-27 10:27:39 +03:00
@EnableCosmosRepositories
2019-10-21 17:35:53 +03:00
@Slf4j
2019-09-27 10:27:39 +03:00
public class AppConfiguration extends AbstractCosmosConfiguration {
2017-09-18 09:54:30 +03:00
2018-06-04 06:24:25 +03:00
@Value ("${azure.cosmosdb.uri}")
2017-09-18 09:54:30 +03:00
private String uri;
2018-06-04 06:24:25 +03:00
@Value ("${azure.cosmosdb.key}")
2017-09-18 09:54:30 +03:00
private String key;
2019-08-16 07:06:15 +03:00
@Value ("${azure.cosmosdb.secondaryKey}")
private String secondaryKey;
2018-06-04 06:24:25 +03:00
@Value ("${azure.cosmosdb.database}")
2017-09-18 09:54:30 +03:00
private String dbName;
2019-10-21 17:35:53 +03:00
@Value ("${azure.cosmosdb.populateQueryMetrics}")
private boolean populateQueryMetrics;
2019-08-16 07:06:15 +03:00
private CosmosKeyCredential cosmosKeyCredential;
2017-09-18 09:54:30 +03:00
2019-09-27 10:27:39 +03:00
public CosmosDBConfig getConfig() {
2019-08-16 07:06:15 +03:00
this.cosmosKeyCredential = new CosmosKeyCredential(key);
2019-10-21 17:35:53 +03:00
CosmosDbConfig cosmosdbConfig = CosmosDBConfig.builder(uri,
this.cosmosKeyCredential, dbName).build();
cosmosdbConfig.setPopulateQueryMetrics(populateQueryMetrics);
cosmosdbConfig.setResponseDiagnosticsProcessor(new ResponseDiagnosticsProcessorImplementation());
return cosmosdbConfig;
2019-08-16 07:06:15 +03:00
}
public void switchToSecondaryKey() {
this.cosmosKeyCredential.key(secondaryKey);
2017-09-18 09:54:30 +03:00
}
2019-10-21 17:35:53 +03:00
private static class ResponseDiagnosticsProcessorImplementation implements ResponseDiagnosticsProcessor {
@Override
public void processResponseDiagnostics(@Nullable ResponseDiagnostics responseDiagnostics) {
log.info("Response Diagnostics {}", responseDiagnostics);
}
}
2017-09-18 09:54:30 +03:00
}
```
2019-07-27 16:45:43 +03:00
Or if you want to customize your config:
```java
2019-09-27 10:27:39 +03:00
public CosmosDBConfig getConfig() {
2019-08-16 07:06:15 +03:00
this.cosmosKeyCredential = new CosmosKeyCredential(key);
2019-09-27 10:27:39 +03:00
CosmosDBConfig cosmosDbConfig = CosmosDBConfig.builder(uri, this.cosmosKeyCredential, dbName).build();
cosmosDbConfig.getConnectionPolicy().setConnectionMode(ConnectionMode.DIRECT);
cosmosDbConfig.getConnectionPolicy().setMaxPoolSize(1000);
return cosmosDbConfig;
2019-07-27 16:45:43 +03:00
}
```
2019-09-27 10:27:39 +03:00
By default, `@EnableCosmosRepositories` will scan the current package for any interfaces that extend one of Spring Data's repository interfaces. Using it to annotate your Configuration class to scan a different root package by type if your project layout has multiple projects and it's not finding your repositories.
2018-08-23 05:16:35 +03:00
```java
2017-09-18 09:54:30 +03:00
@Configuration
2019-09-27 10:27:39 +03:00
@EnableCosmosRepositories (basePackageClass=UserRepository.class)
public class AppConfiguration extends AbstractCosmosConfiguration {
2017-09-18 09:54:30 +03:00
// configuration code
}
```
2018-03-09 08:01:35 +03:00
### Define an entity
2018-04-12 07:57:10 +03:00
Define a simple entity as Document in Azure Cosmos DB.
2017-09-18 09:54:30 +03:00
2020-03-09 23:59:37 +03:00
You can define entities by adding the `@Document` annotation and specifying properties related to the container, such as the container name, request units (RUs), time to live, and auto-create container.
Containers are created automatically unless you don't want them to: Set `autoCreateCollection` to false in `@Document` annotation to disable auto creation of containers.
Note: By default request units assigned to newly created containers is 4000. Specify different ru value to customize request units for container created by the SDK (minimum RU value is 400).
2018-08-23 05:16:35 +03:00
```java
2020-03-09 23:59:37 +03:00
@Document (collection = "myCollection", ru = "400")
2017-09-18 09:54:30 +03:00
public class User {
private String id;
private String firstName;
2019-09-27 10:27:39 +03:00
2017-09-18 09:54:30 +03:00
@PartitionKey
private String lastName;
... // setters and getters
2018-03-01 11:01:01 +03:00
public User() {
2018-03-09 08:01:35 +03:00
// If you do not want to create a default constructor,
// use annotation @JsonCreator and @JsonProperty in the full args constructor
2018-03-01 11:01:01 +03:00
}
2017-09-18 09:54:30 +03:00
public User(String id, String firstName, String lastName) {
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
}
@Override
public String toString() {
2019-10-22 01:59:20 +03:00
return String.format("User: %s %s, %s", firstName, lastName, id);
2017-09-18 09:54:30 +03:00
}
}
```
2017-09-19 06:33:20 +03:00
`id` field will be used as document id in Azure Cosmos DB. If you want use another field like `emailAddress` as document `id` , just annotate that field with `@Id` annotation.
2017-09-18 09:54:30 +03:00
2017-09-19 06:33:20 +03:00
Annotation `@Document(collection="mycollection")` is used to specify collection name in Azure Cosmos DB.
Annotation `@PartitionKey` on `lastName` field is used to specify this field be partition key in Azure Cosmos DB.
2017-09-18 09:54:30 +03:00
2018-08-23 05:16:35 +03:00
```java
2017-09-18 09:54:30 +03:00
@Document (collection = "mycollection")
public class User {
@Id
private String emailAddress;
...
}
```
### Create repositories
2019-09-27 10:27:39 +03:00
Extends CosmosRepository interface, which provides Spring Data repository support.
2017-09-18 09:54:30 +03:00
2018-08-23 05:16:35 +03:00
```java
2019-09-27 10:27:39 +03:00
import CosmosRepository;
2017-09-18 09:54:30 +03:00
import org.springframework.stereotype.Repository;
@Repository
2019-09-27 10:27:39 +03:00
public interface UserRepository extends CosmosRepository< User , String > {
2018-01-02 10:37:20 +03:00
List< User > findByFirstName(String firstName);
2017-09-18 09:54:30 +03:00
}
```
2018-01-02 10:37:20 +03:00
`findByFirstName` method is custom query method, it will find documents per FirstName.
2017-09-18 09:54:30 +03:00
### Create an Application class
Here create an application class with all the components
2018-08-23 05:16:35 +03:00
```java
2017-09-18 09:54:30 +03:00
@SpringBootApplication
public class SampleApplication implements CommandLineRunner {
@Autowired
private UserRepository repository;
2019-08-16 07:06:15 +03:00
@Autowired
private ApplicationContext applicationContext;
2017-09-18 09:54:30 +03:00
public static void main(String[] args) {
SpringApplication.run(SampleApplication.class, args);
}
public void run(String... var1) throws Exception {
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);
// if emailAddress is mapped to id, then
// final User result = respository.findOne(testUser.getEmailAddress(), testUser.getLastName());
2019-08-16 07:06:15 +03:00
// Switch to secondary key
UserRepositoryConfiguration bean =
applicationContext.getBean(UserRepositoryConfiguration.class);
bean.switchToSecondaryKey();
// Now repository will use secondary key
repository.save(testUser);
2017-09-18 09:54:30 +03:00
}
}
```
2019-09-27 10:27:39 +03:00
Autowired UserRepository interface, then can do save, delete and find operations. Spring Data Azure Cosmos DB uses the CosmosTemplate to execute the queries behind *find* , *save* methods. You can use the template yourself for more complex queries.
2017-09-18 09:54:30 +03:00
2019-03-12 10:51:48 +03:00
## Snapshots
[![Nexus OSS ](https://img.shields.io/nexus/snapshots/https/oss.sonatype.org/com.microsoft.azure/spring-data-cosmosdb.svg )](https://oss.sonatype.org/content/repositories/snapshots/com/microsoft/azure/spring-data-cosmosdb/)
Snapshots built from `master` branch are available, add [maven repositories ](https://maven.apache.org/settings.html#Repositories ) configuration to your pom file as below.
```xml
< repositories >
< repository >
< id > nexus-snapshots< / id >
< url > https://oss.sonatype.org/content/repositories/snapshots/< / url >
< snapshots >
< enabled > true< / enabled >
< updatePolicy > always< / updatePolicy >
< / snapshots >
< / repository >
< / repositories >
```
2017-09-19 06:33:20 +03:00
## Filing Issues
2018-04-13 04:30:25 +03:00
If you encounter any bug, please file an issue [here ](https://github.com/Microsoft/spring-data-cosmosdb/issues/new ).
2017-09-19 06:33:20 +03:00
To suggest a new feature or changes that could be made, file an issue the same way you would for a bug.
2017-09-28 11:13:33 +03:00
## How To Contribute
2017-09-19 06:33:20 +03:00
2017-09-28 11:13:33 +03:00
Contribution is welcome. Please follow [this instruction ](./HowToContribute.md ) to contribute code.
2017-09-19 06:33:20 +03:00
## Code of Conduct
This project has adopted the [Microsoft Open Source Code of Conduct ](https://opensource.microsoft.com/codeofconduct/ ). For more information see the [Code of Conduct FAQ ](https://opensource.microsoft.com/codeofconduct/faq/ ) or contact [opencode@microsoft.com ](mailto:opencode@microsoft.com ) with any additional questions or comments.
2019-03-04 04:44:47 +03:00
### Data/Telemetry
This project collects usage data and sends it to Microsoft to help improve our products and services. Read our [privacy ](https://privacy.microsoft.com/en-us/privacystatement ) statement to learn more.
2020-02-08 05:15:22 +03:00
<!-- URL List -->
[Branch Master Badge]:https://img.shields.io/maven-central/v/com.microsoft.azure/spring-data-cosmosdb/2.2.svg
[Branch 2.1.x Badge]:https://img.shields.io/maven-central/v/com.microsoft.azure/spring-data-cosmosdb/2.1.svg
[Branch 2.0.x Badge]:https://img.shields.io/maven-central/v/com.microsoft.azure/spring-data-cosmosdb/2.0.svg
[Branch Master Link]:https://search.maven.org/search?q=g:com.microsoft.azure%20AND%20a:spring-data-cosmosdb%20AND%20v:2.2.*
[Branch 2.1.x Link]:https://search.maven.org/search?q=g:com.microsoft.azure%20AND%20a:spring-data-cosmosdb%20AND%20v:2.1.*
[Branch 2.0.x Link]:https://search.maven.org/search?q=g:com.microsoft.azure%20AND%20a:spring-data-cosmosdb%20AND%20v:2.0.*