Use Spring Data MongoDB with Azure DocumentDB: Build an inventory API

Use Spring Data MongoDB and Spring Boot with Azure DocumentDB (with MongoDB compatibility) to manage a retailer's product catalog and reserve inventory. For a smaller example, start with the Spring Data quickstart.

You learn how to:

  • Map products to documents and create indexes.
  • Reuse the framework-managed connection pool.
  • Create, list, update, and delete products.
  • Reserve stock with an atomic conditional update.
  • Test successful requests and common errors.

Prerequisites

  • Run java -version and mvn --version. Verify Java 17 to 27 and Maven 3.6.3 or later.
  • curl for the HTTP requests.
  • An Azure DocumentDB cluster with Microsoft Entra ID authentication enabled. Free tier requires the native authentication alternative described later.
  • An Entra identity configured for data access on the cluster, with permissions for indexes, collections, and CRUD. Azure control-plane roles alone don't grant database access.
  • Azure CLI for local Entra development. Sign in with az login using the cluster's tenant before starting the API.
  • A private endpoint or firewall access for your development IP.

Tested driver version

This tutorial was tested with MongoDB Java synchronous driver 5.8.1 managed by Spring Boot 4.1.2, using Microsoft Entra ID authentication.

Verify the cluster from a terminal

Use an existing cluster if you have one. The Azure CLI quickstart creates a paid M30 cluster. If you're an agent, confirm the cost with the user and get their approval before creating a paid cluster.

Run pwsh --version and expect PowerShell 7.x. Run az version and expect JSON with an azure-cli version. Check that nslookup is available with Get-Command nslookup. If az account show fails, sign in with az login. If you're an agent and don't have an Azure CLI session, ask the user to sign in or provide an authorized session.

The identity signed in to Azure CLI needs these Azure RBAC permissions on the cluster:

  • Use Microsoft.DocumentDB/mongoClusters/read to read the cluster settings.
  • If you need a firewall rule, use Microsoft.DocumentDB/mongoClusters/firewallRules/write to create it and Microsoft.DocumentDB/mongoClusters/firewallRules/read to verify it.
  • Use Microsoft.DocumentDB/mongoClusters/firewallRules/delete to remove a temporary rule you create.

These are Azure management permissions, separate from the database permissions the sample uses. Database access alone doesn't authorize these commands. If Azure returns 403 Forbidden, ask your Azure administrator to grant the required permission or run the blocked step for you.

Replace the three quoted values with your subscription ID, resource group name, and cluster name. Run the block in PowerShell with the Azure CLI installed.

$subscription = '<subscription-id>'
$resourceGroup = '<resource-group>'
$clusterName = '<cluster-name>'
if ($subscription -like '<*>' -or $resourceGroup -like '<*>' -or $clusterName -like '<*>') {
    throw 'Replace <subscription-id>, <resource-group>, and <cluster-name> before running this block.'
}
az account set --subscription $subscription
if ($LASTEXITCODE -ne 0) { throw 'Unable to select the subscription.' }
$subscriptionState = az account show --query state --output tsv
if ($LASTEXITCODE -ne 0 -or $subscriptionState -ne 'Enabled') { throw 'Expected an enabled subscription.' }

$clusterUrl = "https://management.azure.com/subscriptions/$subscription/resourceGroups/$resourceGroup/providers/Microsoft.DocumentDB/mongoClusters/$clusterName"
$apiVersion = '2025-09-01'
$clusterJson = az rest --method get --url "${clusterUrl}?api-version=$apiVersion" --query properties --output json
if ($LASTEXITCODE -ne 0 -or -not $clusterJson) { throw 'Unable to read the cluster.' }
$cluster = $clusterJson | ConvertFrom-Json
if ($cluster.provisioningState -ne 'Succeeded' -or $cluster.clusterStatus -ne 'Ready') {
    throw "Cluster not ready: $($cluster.provisioningState), $($cluster.clusterStatus)."
}
if (-not $cluster.connectionString) { throw 'Unable to retrieve the connection string template.' }
$clusterHost = ([uri] ($cluster.connectionString -replace '^mongodb\+srv://(?:[^/]*@)?', 'https://')).Host
"Cluster host: $clusterHost"
"Server version: $($cluster.serverVersion)"
"Public network access: $($cluster.publicNetworkAccess)"
nslookup -type=SRV "_mongodb._tcp.$clusterHost"
if ($LASTEXITCODE -ne 0) { throw 'SRV lookup failed.' }

Expect the cluster hostname, a server version such as 8.0, and one or more SRV targets. If nslookup doesn't show any SRV targets, stop and check DNS from the machine that runs the sample. Save the hostname for later steps. It typically has the form <cluster-name>.mongocluster.cosmos.azure.com or <cluster-name>.global.mongocluster.cosmos.azure.com. Use the returned hostname instead of constructing it from the cluster name.

Public access only. If the cluster reports Enabled for public network access and no existing rule allows the machine that runs the sample, allow only that machine's public IPv4 address.

If the sample runs behind a proxy or in a cloud sandbox, the IP address that curl returns might change or differ from the address the database sees. Use a reachable private endpoint instead, or stop and ask the user for a stable network path. Don't keep adding firewall rules.

Run curl --version and expect a version line starting with curl. Run the cluster verification and firewall blocks in one PowerShell session. If your tool starts a new session for each command, run both blocks as one script.

$clientIp = curl --fail --silent --show-error --max-time 10 -4 https://ifconfig.me/ip
if ($LASTEXITCODE -ne 0) { throw 'Unable to determine the public IPv4 address.' }
$parsedIp = $null
if (-not [ipaddress]::TryParse($clientIp, [ref]$parsedIp) -or
    $parsedIp.AddressFamily -ne 'InterNetwork' -or $parsedIp.ToString() -ne $clientIp) {
    throw 'Expected a public IPv4 address in dotted-decimal format.'
}

$ruleName = "allow-framework-sample-$($clientIp.Replace('.', '-'))"
$ruleId = "$(([uri]$clusterUrl).AbsolutePath)/firewallRules/$ruleName"
$ruleUrl = "$clusterUrl/firewallRules/${ruleName}?api-version=$apiVersion"
$body = @{ properties = @{ startIpAddress = $clientIp; endIpAddress = $clientIp } } | ConvertTo-Json
$bodyFile = New-TemporaryFile
try {
    Set-Content -LiteralPath $bodyFile.FullName -Value $body -Encoding utf8 -ErrorAction Stop
    az rest --method put --url $ruleUrl --headers 'Content-Type=application/json' --body "@$($bodyFile.FullName)" --output none
    if ($LASTEXITCODE -ne 0) { throw 'Unable to create the firewall rule.' }
} finally {
    Remove-Item -LiteralPath $bodyFile.FullName
}
"Firewall rule ID: $ruleId"
az resource wait --created --ids $ruleId --api-version $apiVersion --interval 5 --timeout 120
if ($LASTEXITCODE -ne 0) { throw 'The firewall rule did not finish provisioning. Check the rule before retrying.' }
az rest --method get --url $ruleUrl --query "properties.{start:startIpAddress,end:endIpAddress}" --output table
if ($LASTEXITCODE -ne 0) { throw 'Unable to verify the firewall rule.' }

Expect the same IPv4 address in the Start and End columns. If you created the rule for this sample, save the value after Firewall rule ID: for cleanup. If you rerun the block from the same public IPv4 address, it updates the same rule instead of creating another one.

Firewall changes can take up to 15 minutes to propagate. If the initial connection times out after you create the rule, retry the connection every 2 minutes, for up to 15 minutes after you create the rule. Stop if the connection succeeds or returns a different error. Don't recreate the rule while you wait.

For private access, skip the firewall block and run the sample from a machine that can resolve and reach the private endpoint. Don't enable public access just to run the sample.

Follow only the authentication path that your example uses.

Microsoft Entra ID. Follow the CLI steps to enable Microsoft Entra ID authentication and assign a data-plane identity. Azure resource permissions alone don't grant database access. Put the discovered hostname in the example's credential-free URI. Skip the password steps and don't reuse a password-based URI.

Password authentication. If your environment already provides the connection variable the sample needs (MONGODB_URI, or DATABASE_URL for Prisma), skip URI construction.

az rest returns a connection string template, not the password. To find the native administrator username, add $cluster.administrator.userName at the end of the cluster verification block.

  • Agents (noninteractive). Ask the user to set DOCUMENTDB_USERNAME and DOCUMENTDB_PASSWORD as environment variables through your tool's secret settings. Don't ask for credentials in chat, put them in command text, or reset the password.

  • Interactive PowerShell. In PowerShell 7.1 or later, run the following commands in the same session you use to build the URI. Enter your existing credentials at the prompts. Don't put the password in command text.

    $env:DOCUMENTDB_USERNAME = Read-Host 'Native username'
    $env:DOCUMENTDB_PASSWORD = Read-Host 'Native password' -MaskInput
    

Replace <cluster-host> with the hostname from the verification output. Run this block to set MONGODB_URI without printing the credentials or the URI. You don't need variables from the cluster verification session.

$clusterHost = '<cluster-host>'
if ($clusterHost -like '<*>') { throw 'Replace <cluster-host> with the hostname from the verification output.' }
if ([string]::IsNullOrWhiteSpace($env:DOCUMENTDB_USERNAME) -or
    [string]::IsNullOrEmpty($env:DOCUMENTDB_PASSWORD)) {
    throw 'Set DOCUMENTDB_USERNAME and DOCUMENTDB_PASSWORD before building the URI. If you are an agent, ask the user to supply them through your tool''s secret settings.'
}
try {
    $encodedUser = [uri]::EscapeDataString($env:DOCUMENTDB_USERNAME)
    $encodedPassword = [uri]::EscapeDataString($env:DOCUMENTDB_PASSWORD)
    $env:MONGODB_URI = "mongodb+srv://${encodedUser}:${encodedPassword}@${clusterHost}/?tls=true&authSource=admin&authMechanism=SCRAM-SHA-256&retryWrites=false&serverSelectionTimeoutMS=30000"
} finally {
    Remove-Variable encodedUser, encodedPassword -ErrorAction SilentlyContinue
    Remove-Item Env:DOCUMENTDB_USERNAME, Env:DOCUMENTDB_PASSWORD -ErrorAction SilentlyContinue
}

Prisma only. If your environment already provides DATABASE_URL, skip this step. Otherwise, replace <database-name> with the database name in your Prisma example. Run this block in the same PowerShell session as URI construction to add the database name to the URI path and set DATABASE_URL. If your tool starts a new session for each command, run both blocks as one script.

$databaseName = '<database-name>'
if ($databaseName -like '<*>') { throw 'Replace <database-name> with the database name in your Prisma example.' }
$env:DATABASE_URL = $env:MONGODB_URI.Replace('/?', "/${databaseName}?")
Remove-Item Env:MONGODB_URI

Save the URI for a new shell

If your sample loads .env, you can save the URI there to run the sample in a new shell. If you haven't created the project yet, continue to the project setup in your article before running these steps. Use a private local workspace because .env stores the URI in plaintext.

  1. In the sample project directory, run git --version and expect a Git version.

  2. If the project isn't in a Git repository, run git init. Add .env to .gitignore and keep any other settings the sample requires in .env.

  3. Run the following block in the PowerShell session where you set MONGODB_URI or DATABASE_URL. If your tool starts a new session for each command, run URI construction, the Prisma step if applicable, and this block as one script.

    $uriKey = 'MONGODB_URI' # Use 'DATABASE_URL' for Prisma.
    $uriValue = [Environment]::GetEnvironmentVariable($uriKey)
    if (-not $uriValue) { throw "Set $uriKey before writing .env." }
    git check-ignore -q -- .env
    if ($LASTEXITCODE -ne 0) { throw 'Make sure .env is ignored and not tracked by Git.' }
    if ((Test-Path -LiteralPath .env) -and (Select-String -Quiet -LiteralPath .env -Pattern "^\s*(?:export\s+)?${uriKey}\s*=")) {
        throw "Remove the existing $uriKey line from .env before running this block."
    }
    Add-Content -LiteralPath .env -Value "`n$uriKey=$uriValue" -Encoding utf8 -ErrorAction Stop
    Remove-Variable uriValue
    Remove-Item "Env:$uriKey"
    "Saved $uriKey to the ignored .env file."
    

    Expect Saved MONGODB_URI to the ignored .env file. or Saved DATABASE_URL to the ignored .env file. You can now continue with the article in a new shell. Run the sample from the project directory.

If the sample doesn't load .env or you can't store secrets in the workspace, configure your tool to pass the URI to each command that needs it. Alternatively, run URI construction and the sample as one script.

When you're done, remove the connection entry from .env if you added it. Clear any URI variables with Remove-Item Env:MONGODB_URI, Env:DATABASE_URL -ErrorAction SilentlyContinue. Don't print or commit connection strings.

Important

This API is for local development and doesn't authenticate HTTP callers. Add authentication, authorization, HTTPS, and rate limits before exposure. For production database access, use managed identity, private endpoints, and disabled public network access. The Entra callback uses DefaultAzureCredential, which can use your Azure CLI session locally and managed identity in Azure.

Already using Spring Data MongoDB?

If your app uses Spring Data JPA entities or relational repositories, stop: they aren't interchangeable with MongoDB documents and repositories. For an existing Spring Boot 4 MongoDB app, set spring.mongodb.uri and spring.mongodb.database as shown in Create the project. This change doesn't copy documents, indexes, or users. Use Migration options to plan data movement and provision database users separately.

Spring Boot 4.1.2 manages compatible Spring Data and driver versions in this example. Don't override the MongoDB driver independently without checking compatibility.

Understand the scenario

Use database adventureworks_spring and collection products. Products have a unique SKU, name, category, price in integer cents, and nonnegative quantity. This single-currency example accepts signed 32-bit integer inputs.

Method Endpoint Purpose
POST /products Create a product.
GET /products?category=gear&page=1 List 20 products in stable name and ID order.
PATCH /products/:id Update name, category, or price.
POST /products/:id/reserve Decrease quantity if sufficient stock remains.
DELETE /products/:id Delete a product.

The stock filter prevents negative inventory, not duplicate reservations. A timeout can leave the outcome unknown. Driver-managed retries differ from starting a new application operation; add persisted reservation identifiers and concurrency-safe deduplication before application-level retries.

Create the project

  1. Create a directory named documentdb-spring-inventory and open it. Create pom.xml.

    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
      <modelVersion>4.0.0</modelVersion>
      <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>4.1.2</version>
        <relativePath/>
      </parent>
      <groupId>com.example</groupId>
      <artifactId>documentdb-spring-inventory</artifactId>
      <version>1.0.0</version>
      <properties><java.version>17</java.version></properties>
      <dependencies>
        <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-data-mongodb</artifactId>
        </dependency>
        <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-validation</artifactId>
        </dependency>
        <dependency>
          <groupId>com.azure</groupId>
          <artifactId>azure-identity</artifactId>
          <version>1.19.0</version>
        </dependency>
      </dependencies>
      <build><plugins><plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
      </plugin></plugins></build>
    </project>
    
  2. Create src/main/resources/application.properties.

    spring.mongodb.uri=${MONGODB_URI}
    spring.mongodb.database=${MONGODB_DATABASE}
    server.address=127.0.0.1
    server.port=3000
    server.error.include-message=never
    server.error.include-stacktrace=never
    spring.jackson.deserialization.fail-on-unknown-properties=true
    spring.jackson.deserialization.accept-float-as-int=false
    
  3. Add target/ to .gitignore. Set the environment variables in the terminal that runs Maven. On PowerShell:

    $env:MONGODB_AUTH = 'entra'
    $env:MONGODB_URI = 'mongodb+srv://<cluster-host>/?tls=true&retryWrites=false&serverSelectionTimeoutMS=30000'
    $env:MONGODB_DATABASE = 'adventureworks_spring'
    

    On macOS or Linux:

    export MONGODB_AUTH='entra'
    export MONGODB_URI='mongodb+srv://<cluster-host>/?tls=true&retryWrites=false&serverSelectionTimeoutMS=30000'
    export MONGODB_DATABASE='adventureworks_spring'
    

    Use the hostname from Verify the cluster from a terminal. Don't include credentials or SCRAM options in the Entra URI. To use native authentication instead, set MONGODB_AUTH=password and keep the password URI from the terminal setup. Don't put secrets in shell history or source control. retryWrites=false is a sample setting, not a service requirement.

Implement the model and API

Create src/main/java/com/example/inventory/Application.java:

package com.example.inventory;

import java.util.Map;
import java.util.Set;
import java.util.List;
import java.time.Duration;
import java.time.OffsetDateTime;
import com.azure.core.credential.TokenRequestContext;
import com.azure.identity.DefaultAzureCredentialBuilder;
import com.mongodb.MongoCredential;
import tools.jackson.databind.JsonNode;
import jakarta.validation.Valid;
import jakarta.validation.ConstraintViolationException;
import jakarta.validation.constraints.*;
import org.bson.types.ObjectId;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.mongodb.autoconfigure.MongoClientSettingsBuilderCustomizer;
import org.springframework.beans.factory.SmartInitializingSingleton;
import org.springframework.context.annotation.Bean;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.data.annotation.Id;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.FindAndModifyOptions;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.index.Index;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.method.annotation.HandlerMethodValidationException;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;

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

    @Bean
    MongoClientSettingsBuilderCustomizer authentication() {
        String auth = System.getenv("MONGODB_AUTH");
        if ("password".equals(auth)) return settings -> {};
        if (!"entra".equals(auth)) throw new IllegalArgumentException("Set MONGODB_AUTH to entra or password.");
        var credential = new DefaultAzureCredentialBuilder().build();
        MongoCredential.OidcCallback callback = context -> {
            var token = credential.getToken(new TokenRequestContext()
                .addScopes("https://ossrdbms-aad.database.windows.net/.default"))
                .block(context.getTimeout());
            if (token == null) throw new IllegalStateException("Entra ID didn't return an access token.");
            return new MongoCredential.OidcCallbackResult(token.getToken(),
                Duration.between(OffsetDateTime.now(), token.getExpiresAt()));
        };
        var mongoCredential = MongoCredential.createOidcCredential(null)
            .withMechanismProperty("OIDC_CALLBACK", callback);
        return settings -> settings.credential(mongoCredential);
    }

    @Bean
    SmartInitializingSingleton indexes(MongoTemplate template) {
        return () -> {
            template.indexOps(Product.class).createIndex(new Index().on("sku", Sort.Direction.ASC).unique());
            template.indexOps(Product.class).createIndex(new Index().on("category", Sort.Direction.ASC)
                .on("name", Sort.Direction.ASC).on("_id", Sort.Direction.ASC));
        };
    }

    @Document("products")
    public static class Product {
        @Id public ObjectId id;
        public String sku;
        public String name;
        public String category;
        public int priceCents;
        public int quantity;
    }

    public record CreateProduct(@NotBlank @Size(max=64) String sku,
        @NotBlank @Size(max=200) String name, @NotBlank @Size(max=100) String category,
        @NotNull @PositiveOrZero Integer priceCents, @NotNull @PositiveOrZero Integer quantity) {}
    public record Reservation(@NotNull @Positive Integer quantity) {}
    public record ProductView(String _id, String sku, String name, String category, int priceCents, int quantity) {}
    public record Page(int page, List<ProductView> products) {}

    static ProductView output(Product product) {
        return new ProductView(product.id.toHexString(), product.sku, product.name,
            product.category, product.priceCents, product.quantity);
    }

    static Query identity(String id) {
        if (!ObjectId.isValid(id)) throw new IllegalArgumentException("Invalid product ID.");
        return Query.query(Criteria.where("_id").is(new ObjectId(id)));
    }

    @RestController
    static class ProductApi {
        private static final int PAGE_SIZE = 20;
        private final MongoTemplate template;
        ProductApi(MongoTemplate template) { this.template = template; }

        @PostMapping("/products")
        ResponseEntity<ProductView> create(@Valid @RequestBody CreateProduct body) {
            Product product = new Product();
            product.sku = body.sku().trim();
            product.name = body.name().trim();
            product.category = body.category().trim();
            product.priceCents = body.priceCents();
            product.quantity = body.quantity();
            return ResponseEntity.status(201).body(output(template.insert(product)));
        }

        @GetMapping("/products")
        Page list(@RequestParam String category, @RequestParam(defaultValue="1") @Min(1) @Max(1000) int page) {
            String filter = category.trim();
            if (filter.isEmpty() || filter.length() > 100) throw new IllegalArgumentException("Invalid category.");
            Query query = Query.query(Criteria.where("category").is(filter))
                .with(Sort.by("name", "_id")).skip((page - 1L) * PAGE_SIZE).limit(PAGE_SIZE);
            return new Page(page, template.find(query, Product.class).stream().map(Application::output).toList());
        }

        @PatchMapping("/products/{id}")
        ResponseEntity<?> patch(@PathVariable String id, @RequestBody JsonNode body) {
            Query query = identity(id);
            if (!body.isObject() || body.isEmpty()) throw new IllegalArgumentException("Provide fields.");
            Update update = new Update();
            body.properties().forEach(field -> {
                String key = field.getKey();
                JsonNode value = field.getValue();
                if (!Set.of("name", "category", "priceCents").contains(key))
                    throw new IllegalArgumentException("Invalid field.");
                if (key.equals("priceCents")) {
                    if (!value.isIntegralNumber() || !value.canConvertToInt() || value.intValue() < 0)
                        throw new IllegalArgumentException("Invalid price.");
                    update.set(key, value.intValue());
                } else {
                    int limit = key.equals("name") ? 200 : 100;
                    if (!value.isTextual() || value.textValue().trim().isEmpty() || value.textValue().trim().length() > limit)
                        throw new IllegalArgumentException("Invalid text.");
                    update.set(key, value.textValue().trim());
                }
            });
            Product updated = template.findAndModify(query, update, FindAndModifyOptions.options().returnNew(true), Product.class);
            return updated == null ? ResponseEntity.status(404).body(Map.of("error", "Product not found."))
                : ResponseEntity.ok(output(updated));
        }

        @PostMapping("/products/{id}/reserve")
        ResponseEntity<?> reserve(@PathVariable String id, @Valid @RequestBody Reservation body) {
            Query query = identity(id).addCriteria(Criteria.where("quantity").gte(body.quantity()));
            Product updated = template.findAndModify(query, new Update().inc("quantity", -body.quantity()),
                FindAndModifyOptions.options().returnNew(true), Product.class);
            return updated == null ? ResponseEntity.status(409).body(Map.of("error", "Product not found or insufficient inventory."))
                : ResponseEntity.ok(output(updated));
        }

        @DeleteMapping("/products/{id}")
        ResponseEntity<?> delete(@PathVariable String id) {
            Product removed = template.findAndRemove(identity(id), Product.class);
            return removed == null ? ResponseEntity.status(404).body(Map.of("error", "Product not found."))
                : ResponseEntity.noContent().build();
        }
    }

    @RestControllerAdvice
    static class Errors {
        @ExceptionHandler(DuplicateKeyException.class)
        ResponseEntity<?> duplicate() {
            return ResponseEntity.status(409).body(Map.of("error", "SKU already exists."));
        }

        @ExceptionHandler({IllegalArgumentException.class, MethodArgumentNotValidException.class,
            HttpMessageNotReadableException.class, MissingServletRequestParameterException.class,
            MethodArgumentTypeMismatchException.class, HandlerMethodValidationException.class,
            ConstraintViolationException.class})
        ResponseEntity<?> invalid() {
            return ResponseEntity.badRequest().body(Map.of("error", "Invalid request fields or JSON."));
        }

        @ExceptionHandler(DataAccessException.class)
        ResponseEntity<?> failed(DataAccessException error) {
            System.err.println("Request failed: " + error.getClass().getSimpleName());
            return ResponseEntity.status(500).body(Map.of("error", "The request could not be completed."));
        }
    }
}

The managed MongoTemplate shares a connection pool. Index creation runs before the embedded web server starts accepting requests. Only _id is indexed by the service by default. In production, manage index changes as a reviewed deployment operation.

findAndModify checks the stock predicate and decrements quantity atomically, then returns the updated document. A read followed by save() isn't equivalent under concurrency. The sample doesn't create an order or coordinate multiple products. Template writes don't automatically run Jakarta Bean Validation; request DTOs and patch handling validate inputs explicitly. Use cursor pagination for large catalogs and enforce request body limits in production hosting.

Run the application

Reuse Spring Boot's MongoDB configuration and managed MongoTemplate. The inventory routes and HTTP test data are examples, not application infrastructure.

Start the API:

mvn spring-boot:run

The server reports port 3000. Access the API at http://127.0.0.1:3000.

Test the API

Keep the API running and open a second terminal with curl installed. These requests don't require another programming language. On Windows PowerShell, use curl.exe instead of curl to avoid its Invoke-WebRequest alias. Each command prints response headers, including the HTTP status, followed by the JSON body.

  1. Create product.json in the test terminal's working directory. Use a unique SKU for each test run, and keep it unchanged for the duplicate request.

    {
      "sku": "SURF-CURL-001",
      "name": "Yamba Surfboard",
      "category": "gear-surf-surfboards",
      "priceCents": 85000,
      "quantity": 12
    }
    
  2. Create the product. Expect 201, quantity 12, and an _id string. Record this ID and replace <product-id> in the following commands with it.

    curl --include --request POST "http://127.0.0.1:3000/products" --header "Content-Type: application/json" --data-binary "@product.json"
    
  3. Run the same command again. Expect 409 because the SKU already exists.

  4. List products in the category. Expect 200 and a products array. The list returns 20 products per page; your product might be on a later page if the category already contains data.

    curl --include "http://127.0.0.1:3000/products?category=gear-surf-surfboards&page=1"
    
  5. Create price.json:

    { "priceCents": 82000 }
    

    Update the price. Expect 200 and priceCents equal to 82000.

    curl --include --request PATCH "http://127.0.0.1:3000/products/<product-id>" --header "Content-Type: application/json" --data-binary "@price.json"
    
  6. Create reservation.json:

    { "quantity": 2 }
    

    Reserve two units. Expect 200 and quantity 10.

    curl --include --request POST "http://127.0.0.1:3000/products/<product-id>/reserve" --header "Content-Type: application/json" --data-binary "@reservation.json"
    
  7. Change the quantity in reservation.json to 11 and repeat the reservation command. Expect 409 because only 10 units remain. Then change it to -1 and repeat. Expect 400.

  8. Change priceCents in price.json to -1 and repeat the price update command. Expect 400.

  9. Try an invalid ID. Expect 400.

    curl --include --request DELETE "http://127.0.0.1:3000/products/not-an-objectid"
    
  10. Delete only the product created in this test, even if an earlier check failed. Expect 204 with no body. Repeat the command and expect 404.

    curl --include --request DELETE "http://127.0.0.1:3000/products/<product-id>"
    
  11. List the category again. Expect 200 and verify that the deleted _id is no longer present.

    curl --include "http://127.0.0.1:3000/products?category=gear-surf-surfboards&page=1"
    

Remove the three local JSON files when you finish. If you use another API port, replace 3000 in the commands.

Troubleshoot common issues

Symptom Action
Compilation fails. Use Java 17 or later and Spring Boot's managed dependencies.
MongoTimeoutException Run the SRV lookup in the terminal setup from the machine that runs the app.
E11000 Use a dedicated tutorial database without duplicate SKUs.
The API returns 400. Check ObjectIds, JSON shape, required fields, and integer bounds.
The API returns 409. Check duplicate SKUs or insufficient inventory.

Spring startup diagnostics can contain connection details. Redact them before sharing. API responses don't expose database diagnostics.

Clean up resources

The test deletes its product but leaves the collection and indexes.

  1. Stop the API with Ctrl+C.
  2. Delete only the adventureworks_spring database if you no longer need it.
  3. Delete the cluster only if you created it exclusively for this tutorial.
  4. Remove temporary firewall rules and clear the temporary environment variables.