├── CHANGELOG.md
├── .gitignore
├── .devcontainer
└── devcontainer.json
├── src
└── main
│ ├── resources
│ └── application.properties
│ └── java
│ └── com
│ └── azure
│ └── cosmos
│ └── springexamples
│ ├── quickstart
│ └── sync
│ │ ├── ReactiveUserRepository.java
│ │ ├── CosmosProperties.java
│ │ ├── SampleAppConfiguration.java
│ │ ├── SampleApplication.java
│ │ └── UserRepository.java
│ ├── common
│ └── User.java
│ └── featureexamples
│ └── Pagination.java
├── .github
├── CODE_OF_CONDUCT.md
├── ISSUE_TEMPLATE.md
└── PULL_REQUEST_TEMPLATE.md
├── LICENSE.md
├── README.md
├── pom.xml
└── CONTRIBUTING.md
/CHANGELOG.md:
--------------------------------------------------------------------------------
1 | ## [project-title] Changelog
2 |
3 |
4 | # x.y.z (yyyy-mm-dd)
5 |
6 | *Features*
7 | * ...
8 |
9 | *Bug Fixes*
10 | * ...
11 |
12 | *Breaking Changes*
13 | * ...
14 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | target/
2 | pom.xml.tag
3 | pom.xml.releaseBackup
4 | pom.xml.versionsBackup
5 | pom.xml.next
6 | release.properties
7 | dependency-reduced-pom.xml
8 | buildNumber.properties
9 | .mvn/timing.properties
10 | # https://github.com/takari/maven-wrapper#usage-without-binary-jar
11 | .mvn/wrapper/maven-wrapper.jar
12 | .idea
13 | *.iml
--------------------------------------------------------------------------------
/.devcontainer/devcontainer.json:
--------------------------------------------------------------------------------
1 | {
2 | "image": "mcr.microsoft.com/devcontainers/java:0-17",
3 | "features": {
4 | "ghcr.io/devcontainers/features/java:1": {
5 | "version": "none",
6 | "installMaven": "true",
7 | "mavenVersion": "3.8.6",
8 | "installGradle": "false"
9 | }
10 | }
11 | }
--------------------------------------------------------------------------------
/src/main/resources/application.properties:
--------------------------------------------------------------------------------
1 | cosmos.uri=${ACCOUNT_HOST}
2 | cosmos.key=${ACCOUNT_KEY}
3 | cosmos.secondaryKey=${SECONDARY_ACCOUNT_KEY}
4 |
5 | dynamic.collection.name=spel-property-collection
6 | # Set to true to populate query metrics -
7 | # NOTE: this will NOT give request information about point reads (only queries)
8 | cosmos.queryMetricsEnabled=true
9 | # See https://aka.ms/PointReadsInSpring for more information on the difference between point reads and queries.
10 |
--------------------------------------------------------------------------------
/.github/CODE_OF_CONDUCT.md:
--------------------------------------------------------------------------------
1 | # Microsoft Open Source Code of Conduct
2 |
3 | This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/).
4 |
5 | Resources:
6 |
7 | - [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/)
8 | - [Microsoft Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/)
9 | - Contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with questions or concerns
10 |
--------------------------------------------------------------------------------
/src/main/java/com/azure/cosmos/springexamples/quickstart/sync/ReactiveUserRepository.java:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft Corporation. All rights reserved.
2 | // Licensed under the MIT License.
3 | package com.azure.cosmos.springexamples.quickstart.sync;
4 |
5 | import com.azure.cosmos.springexamples.common.User;
6 | import com.azure.spring.data.cosmos.repository.Query;
7 | import com.azure.spring.data.cosmos.repository.ReactiveCosmosRepository;
8 | import org.springframework.stereotype.Repository;
9 | import reactor.core.publisher.Flux;
10 |
11 | @Repository
12 | public interface ReactiveUserRepository extends ReactiveCosmosRepository {
13 |
14 | @Query(value = "SELECT * FROM users u WHERE u.firstName = @firstName")
15 | Flux findByFirstName(String firstName);
16 | }
17 |
18 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE.md:
--------------------------------------------------------------------------------
1 |
4 | > Please provide us with the following information:
5 | > ---------------------------------------------------------------
6 |
7 | ### This issue is for a: (mark with an `x`)
8 | ```
9 | - [ ] bug report -> please search issues before submitting
10 | - [ ] feature request
11 | - [ ] documentation issue or request
12 | - [ ] regression (a behavior that used to work and stopped in a new release)
13 | ```
14 |
15 | ### Minimal steps to reproduce
16 | >
17 |
18 | ### Any log messages given by the failure
19 | >
20 |
21 | ### Expected/desired behavior
22 | >
23 |
24 | ### OS and Version?
25 | > Windows 7, 8 or 10. Linux (which distribution). macOS (Yosemite? El Capitan? Sierra?)
26 |
27 | ### Versions
28 | >
29 |
30 | ### Mention any other details that might be useful
31 |
32 | > ---------------------------------------------------------------
33 | > Thanks! We'll be in touch soon.
34 |
--------------------------------------------------------------------------------
/.github/PULL_REQUEST_TEMPLATE.md:
--------------------------------------------------------------------------------
1 | ## Purpose
2 |
3 | * ...
4 |
5 | ## Does this introduce a breaking change?
6 |
7 | ```
8 | [ ] Yes
9 | [ ] No
10 | ```
11 |
12 | ## Pull Request Type
13 | What kind of change does this Pull Request introduce?
14 |
15 |
16 | ```
17 | [ ] Bugfix
18 | [ ] Feature
19 | [ ] Code style update (formatting, local variables)
20 | [ ] Refactoring (no functional changes, no api changes)
21 | [ ] Documentation content changes
22 | [ ] Other... Please describe:
23 | ```
24 |
25 | ## How to Test
26 | * Get the code
27 |
28 | ```
29 | git clone [repo-address]
30 | cd [repo-name]
31 | git checkout [branch-name]
32 | npm install
33 | ```
34 |
35 | * Test the code
36 |
37 | ```
38 | ```
39 |
40 | ## What to Check
41 | Verify that the following are valid
42 | * ...
43 |
44 | ## Other Information
45 |
--------------------------------------------------------------------------------
/LICENSE.md:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) Microsoft Corporation.
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE
--------------------------------------------------------------------------------
/src/main/java/com/azure/cosmos/springexamples/quickstart/sync/CosmosProperties.java:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft Corporation. All rights reserved.
2 | // Licensed under the MIT License.
3 | package com.azure.cosmos.springexamples.quickstart.sync;
4 |
5 | import org.springframework.boot.context.properties.ConfigurationProperties;
6 |
7 | @ConfigurationProperties(prefix = "cosmos")
8 | public class CosmosProperties {
9 |
10 | private String uri;
11 |
12 | private String key;
13 |
14 | private String secondaryKey;
15 |
16 | private boolean queryMetricsEnabled;
17 |
18 | public String getUri() {
19 | return uri;
20 | }
21 |
22 | public void setUri(String uri) {
23 | this.uri = uri;
24 | }
25 |
26 | public String getKey() {
27 | return key;
28 | }
29 |
30 | public void setKey(String key) {
31 | this.key = key;
32 | }
33 |
34 | public String getSecondaryKey() {
35 | return secondaryKey;
36 | }
37 |
38 | public void setSecondaryKey(String secondaryKey) {
39 | this.secondaryKey = secondaryKey;
40 | }
41 |
42 | public boolean isQueryMetricsEnabled() {
43 | return queryMetricsEnabled;
44 | }
45 |
46 | public void setQueryMetricsEnabled(boolean enableQueryMetrics) {
47 | this.queryMetricsEnabled = enableQueryMetrics;
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/src/main/java/com/azure/cosmos/springexamples/common/User.java:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft Corporation. All rights reserved.
2 | // Licensed under the MIT License.
3 | package com.azure.cosmos.springexamples.common;
4 |
5 | import com.azure.spring.data.cosmos.core.mapping.Container;
6 | import com.azure.spring.data.cosmos.core.mapping.PartitionKey;
7 |
8 | @Container(containerName = "usercontainer")
9 | public class User {
10 | private String id;
11 | private String firstName;
12 |
13 |
14 | @PartitionKey
15 | private String lastName;
16 |
17 | public User() {
18 | }
19 |
20 | public User(String id, String firstName, String lastName) {
21 | this.id = id;
22 | this.firstName = firstName;
23 | this.lastName = lastName;
24 | }
25 |
26 | @Override
27 | public String toString() {
28 | return String.format("com.azure.spring.data.cosmos.User: %s %s, %s", firstName, lastName, id);
29 | }
30 |
31 | public String getId() {
32 | return id;
33 | }
34 |
35 | public void setId(String id) {
36 | this.id = id;
37 | }
38 |
39 | public String getFirstName() {
40 | return firstName;
41 | }
42 |
43 | public void setFirstName(String firstName) {
44 | this.firstName = firstName;
45 | }
46 |
47 | public String getLastName() {
48 | return lastName;
49 | }
50 |
51 | public void setLastName(String lastName) {
52 | this.lastName = lastName;
53 | }
54 | }
55 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | **The samples in this repo have moved [here](https://github.com/Azure-Samples/azure-spring-boot-samples/tree/main/cosmos/azure-spring-data-cosmos/spring3-samples/cosmos-quickstart-samples). This repo is no longer maintained**.
2 |
3 |
4 | # Azure Cosmos DB for NoSQL & Spring Data sample
5 |
6 | Azure Cosmos DB for NoSQL & Spring Data sample code
7 |
8 | ## Features
9 |
10 | This repo provides basic sample code for getting started with Azure Cosmos DB for NoSQL SQL API using the `azure-spring-data-cosmos` library for Java.
11 |
12 | ## Getting Started
13 |
14 | ### Prerequisites
15 |
16 | - `Java Development Kit 8` or `JDK 11` if you run the `azure-spring-data-cosmos-java-11-getting-started`.
17 | - An active Azure Cosmos DB for NoSQL account. If you don't have an Azure subscription, you can sign up for a [free subscription for Azure](https://azure.microsoft.com/free/).
18 | - Alternatively, you can use [Try Azure Cosmos DB free](https://cosmos.azure.com/try) for development and testing.
19 | - As another alternative, you can use the [Azure Cosmos DB emulator](https://docs.microsoft.com/en-us/azure/cosmos-db/local-emulator).
20 | - (Optional) SLF4J is a logging facade.
21 | - (Optional) [SLF4J binding](http://www.slf4j.org/manual.html) is used to associate a specific logging framework with SLF4J.
22 | - (Optional) Maven.
23 |
24 | 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](http://www.slf4j.org/manual.html) for more information.
25 |
26 | ### GitHub Codespaces
27 |
28 | [](https://github.com/codespaces/new?hide_repo_select=true&ref=main&repo=287104556)
29 |
30 | ### Quickstart
31 |
32 | 1. In an empty directory, clone the repository: `git clone https://github.com/Azure-Samples/azure-spring-data-cosmos-java-sql-api-samples.git .`
33 | 1. Update the **src/main/resources/application.properties** file with the **uri**, **primary key**, and **secondary key* from your Azure Cosmos DB for NoSQL account.
34 | 3. Run the application: `mvn spring-boot:run`
35 |
36 | ## Resources
37 |
38 | Please refer to Spring Data for Azure Cosmos DB for NoSQL [source code](https://github.com/Azure/azure-sdk-for-java/tree/master/sdk/cosmos) for more information.
39 |
--------------------------------------------------------------------------------
/src/main/java/com/azure/cosmos/springexamples/quickstart/sync/SampleAppConfiguration.java:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft Corporation. All rights reserved.
2 | // Licensed under the MIT License.
3 | package com.azure.cosmos.springexamples.quickstart.sync;
4 |
5 | import com.azure.cosmos.CosmosClientBuilder;
6 | import com.azure.cosmos.DirectConnectionConfig;
7 | import com.azure.spring.data.cosmos.config.AbstractCosmosConfiguration;
8 | import com.azure.spring.data.cosmos.config.CosmosConfig;
9 | import com.azure.spring.data.cosmos.core.ResponseDiagnostics;
10 | import com.azure.spring.data.cosmos.core.ResponseDiagnosticsProcessor;
11 | import com.azure.spring.data.cosmos.repository.config.EnableCosmosRepositories;
12 | import com.azure.spring.data.cosmos.repository.config.EnableReactiveCosmosRepositories;
13 | import org.slf4j.Logger;
14 | import org.slf4j.LoggerFactory;
15 | import org.springframework.beans.factory.annotation.Autowired;
16 | import org.springframework.boot.context.properties.EnableConfigurationProperties;
17 | import org.springframework.context.annotation.Bean;
18 | import org.springframework.context.annotation.Configuration;
19 | import org.springframework.context.annotation.PropertySource;
20 | import org.springframework.lang.Nullable;
21 |
22 | @Configuration
23 | @EnableConfigurationProperties(CosmosProperties.class)
24 | @EnableCosmosRepositories
25 | @EnableReactiveCosmosRepositories
26 | @PropertySource("classpath:application.properties")
27 | public class SampleAppConfiguration extends AbstractCosmosConfiguration {
28 | private static final Logger logger = LoggerFactory.getLogger(SampleAppConfiguration.class);
29 |
30 | @Autowired
31 | private CosmosProperties properties;
32 |
33 | @Bean
34 | public CosmosClientBuilder cosmosClientBuilder() {
35 | DirectConnectionConfig directConnectionConfig = DirectConnectionConfig.getDefaultConfig();
36 | return new CosmosClientBuilder()
37 | .endpoint(properties.getUri())
38 | .key(properties.getKey())
39 | .directMode(directConnectionConfig);
40 | }
41 |
42 | @Bean
43 | public CosmosConfig cosmosConfig() {
44 | return CosmosConfig.builder()
45 | .responseDiagnosticsProcessor(new ResponseDiagnosticsProcessorImplementation())
46 | .enableQueryMetrics(properties.isQueryMetricsEnabled())
47 | .build();
48 | }
49 |
50 | @Override
51 | protected String getDatabaseName() {
52 | return "sampledatabase";
53 | }
54 |
55 | private static class ResponseDiagnosticsProcessorImplementation implements ResponseDiagnosticsProcessor {
56 |
57 | @Override
58 | public void processResponseDiagnostics(@Nullable ResponseDiagnostics responseDiagnostics) {
59 | logger.info("Response Diagnostics {}", responseDiagnostics);
60 | }
61 | }
62 | }
63 |
--------------------------------------------------------------------------------
/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 | 4.0.0
6 |
7 | com.azure
8 | azure-spring-data-cosmos-java-sql-api-samples
9 | 1.0-SNAPSHOT
10 |
11 |
12 | 2.7.1
13 | LATEST
14 |
15 |
16 |
17 |
18 | com.azure
19 | azure-spring-data-cosmos
20 | ${azure.spring.data.cosmos.version}
21 |
22 |
23 | org.springframework
24 | spring-core
25 |
26 |
27 | org.springframework
28 | spring-context
29 |
30 |
31 | org.springframework
32 | spring-beans
33 |
34 |
35 | org.springframework.boot
36 | spring-boot-starter-test
37 |
38 |
39 | org.slf4j
40 | slf4j-simple
41 | test
42 |
43 |
44 |
45 |
46 |
47 |
48 | org.springframework.boot
49 | spring-boot-dependencies
50 | ${spring.boot.version}
51 | pom
52 | import
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 | maven-compiler-plugin
61 | 3.8.1
62 |
63 | 1.8
64 | 1.8
65 |
66 |
67 |
68 | org.springframework.boot
69 | spring-boot-maven-plugin
70 |
71 | com.azure.cosmos.springexamples.quickstart.sync.SampleApplication
72 |
73 |
74 |
75 |
76 |
77 |
--------------------------------------------------------------------------------
/CONTRIBUTING.md:
--------------------------------------------------------------------------------
1 | # Contributing to [project-title]
2 |
3 | This project welcomes contributions and suggestions. Most contributions require you to agree to a
4 | Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us
5 | the rights to use your contribution. For details, visit https://cla.opensource.microsoft.com.
6 |
7 | When you submit a pull request, a CLA bot will automatically determine whether you need to provide
8 | a CLA and decorate the PR appropriately (e.g., status check, comment). Simply follow the instructions
9 | provided by the bot. You will only need to do this once across all repos using our CLA.
10 |
11 | This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/).
12 | For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or
13 | contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments.
14 |
15 | - [Code of Conduct](#coc)
16 | - [Issues and Bugs](#issue)
17 | - [Feature Requests](#feature)
18 | - [Submission Guidelines](#submit)
19 |
20 | ## Code of Conduct
21 | Help us keep this project open and inclusive. Please read and follow our [Code of Conduct](https://opensource.microsoft.com/codeofconduct/).
22 |
23 | ## Found an Issue?
24 | If you find a bug in the source code or a mistake in the documentation, you can help us by
25 | [submitting an issue](#submit-issue) to the GitHub Repository. Even better, you can
26 | [submit a Pull Request](#submit-pr) with a fix.
27 |
28 | ## Want a Feature?
29 | You can *request* a new feature by [submitting an issue](#submit-issue) to the GitHub
30 | Repository. If you would like to *implement* a new feature, please submit an issue with
31 | a proposal for your work first, to be sure that we can use it.
32 |
33 | * **Small Features** can be crafted and directly [submitted as a Pull Request](#submit-pr).
34 |
35 | ## Submission Guidelines
36 |
37 | ### Submitting an Issue
38 | Before you submit an issue, search the archive, maybe your question was already answered.
39 |
40 | If your issue appears to be a bug, and hasn't been reported, open a new issue.
41 | Help us to maximize the effort we can spend fixing issues and adding new
42 | features, by not reporting duplicate issues. Providing the following information will increase the
43 | chances of your issue being dealt with quickly:
44 |
45 | * **Overview of the Issue** - if an error is being thrown a non-minified stack trace helps
46 | * **Version** - what version is affected (e.g. 0.1.2)
47 | * **Motivation for or Use Case** - explain what are you trying to do and why the current behavior is a bug for you
48 | * **Browsers and Operating System** - is this a problem with all browsers?
49 | * **Reproduce the Error** - provide a live example or a unambiguous set of steps
50 | * **Related Issues** - has a similar issue been reported before?
51 | * **Suggest a Fix** - if you can't fix the bug yourself, perhaps you can point to what might be
52 | causing the problem (line of code or commit)
53 |
54 | You can file new issues by providing the above information at the corresponding repository's issues link: https://github.com/[organization-name]/[repository-name]/issues/new].
55 |
56 | ### Submitting a Pull Request (PR)
57 | Before you submit your Pull Request (PR) consider the following guidelines:
58 |
59 | * Search the repository (https://github.com/[organization-name]/[repository-name]/pulls) for an open or closed PR
60 | that relates to your submission. You don't want to duplicate effort.
61 |
62 | * Make your changes in a new git fork:
63 |
64 | * Commit your changes using a descriptive commit message
65 | * Push your fork to GitHub:
66 | * In GitHub, create a pull request
67 | * If we suggest changes then:
68 | * Make the required updates.
69 | * Rebase your fork and force push to your GitHub repository (this will update your Pull Request):
70 |
71 | ```shell
72 | git rebase master -i
73 | git push -f
74 | ```
75 |
76 | That's it! Thank you for your contribution!
77 |
--------------------------------------------------------------------------------
/src/main/java/com/azure/cosmos/springexamples/featureexamples/Pagination.java:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft Corporation. All rights reserved.
2 | // Licensed under the MIT License.
3 | package com.azure.cosmos.springexamples.featureexamples;
4 |
5 | import com.azure.cosmos.springexamples.common.User;
6 | import com.azure.cosmos.springexamples.quickstart.sync.UserRepository;
7 | import com.azure.spring.data.cosmos.core.CosmosTemplate;
8 | import com.azure.spring.data.cosmos.core.query.CosmosPageRequest;
9 | import org.slf4j.Logger;
10 | import org.slf4j.LoggerFactory;
11 | import org.springframework.beans.factory.annotation.Autowired;
12 | import org.springframework.boot.CommandLineRunner;
13 | import org.springframework.boot.SpringApplication;
14 | import org.springframework.boot.autoconfigure.SpringBootApplication;
15 | import org.springframework.context.annotation.ComponentScan;
16 | import org.springframework.data.domain.Page;
17 | import org.springframework.data.domain.PageRequest;
18 | import org.springframework.data.domain.Sort;
19 |
20 | @SpringBootApplication
21 | @ComponentScan(basePackages = "com.azure.cosmos.springexamples.*")
22 | public class Pagination implements CommandLineRunner {
23 | private final Logger logger = LoggerFactory.getLogger(Pagination.class);
24 |
25 | @Autowired
26 | private UserRepository userRepository;
27 |
28 | @Autowired
29 | private CosmosTemplate cosmosTemplate;
30 |
31 | public static void main(String[] args) {
32 | SpringApplication.run(Pagination.class, args);
33 | }
34 |
35 | public void run(String... var1) {
36 |
37 | final User testUser1 = new User("testId1", "testFirstName", "testLastName1");
38 | final User testUser2 = new User("testId2", "testFirstName", "testLastName2");
39 | final User testUser3 = new User("testId3", "testFirstName", "testLastName3");
40 | final User testUser4 = new User("testId4", "testFirstName", "testLastName4");
41 |
42 | logger.info("Using sync repository");
43 |
44 | //
45 |
46 | userRepository.deleteAll();
47 |
48 | //
49 |
50 | //
51 |
52 | logger.info("Saving user : {}, {}, {}, {}", testUser1, testUser2, testUser3, testUser4);
53 | userRepository.save(testUser1);
54 | userRepository.save(testUser2);
55 | userRepository.save(testUser3);
56 | userRepository.save(testUser4);
57 |
58 | //
59 |
60 | //
61 | // This is how you would perform a pagination query with userRepository.
62 |
63 | //Get page
64 | final PageRequest pageRequest = new CosmosPageRequest(0, 2, null);
65 | final Page page = cosmosTemplate.findAll(pageRequest, User.class, "myContainer");
66 | logger.info("(1) Found user's (query): {}", page.getContent());
67 |
68 | //Get page 2 with continuation token
69 | final Page pageWithContToken = cosmosTemplate.findAll(page.getPageable().next(), User.class, "myContainer");
70 | logger.info("(2) Found user's (query): {}", pageWithContToken.getContent());
71 |
72 | //Get page 2 without continuation token
73 | final PageRequest pageRequest2 = new CosmosPageRequest(1, 2, null);
74 | final Page page2 = cosmosTemplate.findAll(pageRequest2, User.class, "myContainer");
75 | logger.info("(3) Found user's (query): {}", page2.getContent());
76 |
77 | //Get page with sort
78 | final Sort sort = Sort.by(Sort.Direction.ASC, "lastName");
79 | final PageRequest pageRequestWithSort = new CosmosPageRequest(0, 2, null, sort);
80 | final Page pageWithSort = cosmosTemplate.findAll(pageRequestWithSort, User.class, "myContainer");
81 | logger.info("(4) Found user's (query): {}", pageWithSort.getContent());
82 |
83 | //Ge page with offset
84 | final PageRequest pageRequestWithOffset = CosmosPageRequest.of(1, 0, 2, null, Sort.by(Sort.Direction.ASC, "lastName"));
85 | final Page pageWithOffset = cosmosTemplate.findAll(pageRequestWithOffset, User.class, "myContainer");
86 | logger.info("(5) Found user's (query): {}", pageWithOffset.getContent());
87 |
88 | //
89 | }
90 | }
91 |
--------------------------------------------------------------------------------
/src/main/java/com/azure/cosmos/springexamples/quickstart/sync/SampleApplication.java:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft Corporation. All rights reserved.
2 | // Licensed under the MIT License.
3 | package com.azure.cosmos.springexamples.quickstart.sync;
4 |
5 | import com.azure.cosmos.models.PartitionKey;
6 | import com.azure.cosmos.springexamples.common.User;
7 | import org.slf4j.Logger;
8 | import org.slf4j.LoggerFactory;
9 | import org.springframework.beans.factory.annotation.Autowired;
10 | import org.springframework.boot.CommandLineRunner;
11 | import org.springframework.boot.SpringApplication;
12 | import org.springframework.boot.autoconfigure.SpringBootApplication;
13 | import reactor.core.publisher.Flux;
14 |
15 | import java.util.ArrayList;
16 | import java.util.Iterator;
17 | import java.util.List;
18 |
19 | @SpringBootApplication
20 | public class SampleApplication implements CommandLineRunner {
21 |
22 | private final Logger logger = LoggerFactory.getLogger(SampleApplication.class);
23 |
24 | @Autowired
25 | private UserRepository userRepository;
26 |
27 | @Autowired
28 | private ReactiveUserRepository reactiveUserRepository;
29 |
30 | public static void main(String[] args) {
31 | SpringApplication.run(SampleApplication.class, args);
32 | }
33 |
34 | public void run(String... var1) {
35 |
36 | final User testUser1 = new User("testId1", "testFirstName", "testLastName1");
37 | final User testUser2 = new User("testId2", "testFirstName", "testLastName2");
38 |
39 | logger.info("Using sync repository");
40 |
41 | //
42 |
43 | userRepository.deleteAll();
44 |
45 | //
46 |
47 | //
48 |
49 | logger.info("Saving user : {}", testUser1);
50 | userRepository.save(testUser1);
51 |
52 | //
53 |
54 | logger.info("Saving user : {}", testUser2);
55 | userRepository.save(testUser2);
56 |
57 | //
58 |
59 | // This is a point read. See https://aka.ms/PointReadsInSpring for more information on the difference between point reads and queries.
60 | final User resultPointRead = userRepository.findById(testUser1.getId(), new PartitionKey(testUser1.getLastName())).get();
61 | logger.info("Found user (point read) : {}", resultPointRead);
62 |
63 | //
64 |
65 | //
66 | // This is functionally the same as above, but is a query. Note that anything defined in userRepository would be a query.
67 | // In order to do point reads in Cosmos DB using Spring, you need to explicitly use findById(String id, PartitionKey partitionKey) as above.
68 | final User resultQuery = userRepository.findByIdAndLastName(testUser1.getId(), testUser1.getLastName());
69 | logger.info("Found user (query): {}", resultQuery);
70 |
71 |
72 | Iterator usersIterator = userRepository.findByFirstName("testFirstName").iterator();
73 |
74 | logger.info("Users by firstName : testFirstName");
75 | while (usersIterator.hasNext()) {
76 | logger.info("user is : {}", usersIterator.next());
77 | }
78 |
79 | // Get all records where last name is in a given array (equivalent to using IN)
80 | logger.info("Users by lastNames list...");
81 | ArrayList lastNames = new ArrayList();
82 | lastNames.add("testLastName1");
83 | lastNames.add("testLastName2");
84 | Iterator usersIterator2 = userRepository.getUsersByLastNameList(lastNames).iterator();
85 | while (usersIterator2.hasNext()) {
86 | logger.info("user is : {}", usersIterator2.next());
87 | }
88 |
89 | logger.info("get all users...");
90 | // Get all records with simple select * from c
91 | Iterator allUsersIterator = userRepository.getAllUsers().iterator();
92 | while (allUsersIterator.hasNext()) {
93 | logger.info("user is : {}", allUsersIterator.next());
94 | }
95 |
96 | logger.info("count all users...");
97 | // Count all records with simple select * from c
98 | final long allUsersCount = userRepository.getUsersWithAggregate();
99 | logger.info("count is : {}", allUsersCount);
100 | //
101 | }
102 | }
103 |
--------------------------------------------------------------------------------
/src/main/java/com/azure/cosmos/springexamples/quickstart/sync/UserRepository.java:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft Corporation. All rights reserved.
2 | // Licensed under the MIT License.
3 | package com.azure.cosmos.springexamples.quickstart.sync;
4 |
5 | import com.azure.cosmos.springexamples.common.User;
6 | import com.azure.spring.data.cosmos.repository.CosmosRepository;
7 | import com.azure.spring.data.cosmos.repository.Query;
8 | import org.springframework.data.repository.query.Param;
9 | import org.springframework.stereotype.Repository;
10 |
11 | import java.util.List;
12 |
13 | @Repository
14 | public interface UserRepository extends CosmosRepository {
15 |
16 | Iterable findByFirstName(String firstName);
17 |
18 | User findByIdAndLastName(String id, String lastName);
19 |
20 | // Query for all documents
21 | @Query(value = "SELECT * FROM c")
22 | List getAllUsers();
23 |
24 | // Get all records where last name is in a given array (equivalent to using IN)
25 | @Query(value = "select * from c where ARRAY_CONTAINS(@lastNames, c.lastName)")
26 | List getUsersByLastNameList(@Param("lastNames") List lastNames);
27 |
28 | // Query for equality using ==
29 | @Query(value = "SELECT * FROM c WHERE c.id = @documentId")
30 | List getUsersWithEquality(@Param("documentId") String documentId);
31 |
32 | // Query for inequality using !=
33 | @Query(value = "SELECT * FROM c WHERE c.id != @documentId")
34 | List getUsersWithInequalityMethod1(@Param("documentId") String documentId);
35 |
36 | // Query for inequality using NOT
37 | @Query(value = "SELECT * FROM c WHERE c.id <> @documentId")
38 | List getUsersWithInequalityMethod2(@Param("documentId") String documentId);
39 |
40 | // Query combining equality and inequality
41 | @Query(value = "SELECT * FROM c WHERE c.lastName = @documentLastName AND c.id != @documentId")
42 | List getUsersWithEqualityAndInequality(@Param("documentLastName") String documentLastName, @Param("documentId") String documentId);
43 |
44 | // Query using range operators like >, <, >=, <=
45 | @Query(value = "SELECT * FROM Families f WHERE f.Children[0].Grade > 5")
46 | List getUsersWithRange();
47 |
48 | // Query using range operators against strings
49 | @Query(value = "SELECT * FROM Families f WHERE f.Address.State > 'NY'")
50 | List getUsersWithRangeAgainstStrings();
51 |
52 | // Query using offset and limit
53 | @Query(value = "select * from c offset @offset limit @limit")
54 | List getUsersWithOffsetLimit(@Param("offset") int offset, @Param("limit") int limit);
55 |
56 | // Query with ORDER BY
57 | @Query(value = "SELECT * FROM Families f WHERE f.LastName = 'Andersen' ORDER BY f.Children[0].Grade")
58 | List getUsersWithOrderBy();
59 |
60 | // Query with DISTINCT
61 | @Query(value = "SELECT DISTINCT c.lastName from c")
62 | List getUsersWithDistinct();
63 |
64 | // Query with aggregate functions
65 | @Query(value = "SELECT VALUE COUNT(1) FROM users")
66 | long getUsersWithAggregate();
67 |
68 | // Query with aggregate functions and a filter
69 | @Query(value = "SELECT VALUE COUNT(f) FROM Families f WHERE f.LastName = 'Andersen'")
70 | long getUsersWithAggregateWithFilter();
71 |
72 | // Query with aggregate functions within documents
73 | @Query(value = "SELECT VALUE COUNT(child) FROM child IN f.Children")
74 | long getUsersWithAggregateWithinDocuments();
75 |
76 | // Work with subdocuments
77 | @Query(value = "SELECT VALUE c FROM c IN f.Children")
78 | List getUsersSubdocuments();
79 |
80 | // Query with single intra-document join
81 | @Query(value = "SELECT f.id FROM Families f JOIN c IN f.Children")
82 | List getUsersWithSingleJoin();
83 |
84 | // Query with two joins
85 | @Query(value = "SELECT f.id as family, c.FirstName AS child, p.GivenName AS pet \" +\n" +
86 | " \"FROM Families f \" +\n" +
87 | " \"JOIN c IN f.Children \" +\n" +
88 | " \"join p IN c.Pets\"")
89 | List getUsersWithTwoJoins();
90 |
91 | // Query with two joins and a filter
92 | @Query(value = "SELECT f.id as family, c.FirstName AS child, p.GivenName AS pet \" +\n" +
93 | " \"FROM Families f \" +\n" +
94 | " \"JOIN c IN f.Children \" +\n" +
95 | " \"join p IN c.Pets \" +\n" +
96 | " \"WHERE p.GivenName = 'Fluffy'")
97 | List getUsersByWithTwoJoinsAndFilter();
98 |
99 | // Query with String STARTSWITH operator
100 | @Query(value = "SELECT * FROM family WHERE STARTSWITH(family.LastName, 'An')")
101 | List getUsersWithStringStartswith();
102 |
103 | // Query with math FLOOR operator
104 | @Query(value = "SELECT VALUE FLOOR(family.Children[0].Grade) FROM family")
105 | List getUsersWithMathFloor();
106 |
107 | // Query with array length operator
108 | @Query(value = "SELECT VALUE ARRAY_LENGTH(family.Children) FROM family")
109 | List getUsersWithArrayLength();
110 | }
111 |
--------------------------------------------------------------------------------