Persisting data with MongoDB

duration 25 minutes

Prerequisites:

Learn how to persist data in your microservices to MongoDB, a document-oriented NoSQL database.

What you’ll learn

You will learn how to use MongoDB to build and test a simple microservice that manages the members of a crew. The microservice will respond to POST, GET, PUT, and DELETE requests that manipulate the database.

The crew members will be stored in MongoDB as documents in the following JSON format:

{
  "_id": {
    "$oid": "5dee6b079503234323db2ebc"
  },
  "Name": "Member1",
  "Rank": "Captain",
  "CrewID": "000001"
}

This microservice connects to MongoDB by using Transport Layer Security (TLS) and injects a MongoDatabase instance into the service with a Contexts and Dependency Injection (CDI) producer. Additionally, MicroProfile Config is used to easily configure the MongoDB driver.

For more information about CDI and MicroProfile Config, see the guides on Injecting dependencies into microservices and Separating configuration from code in microservices.

Additional prerequisites

You will use Docker to run an instance of MongoDB for a fast installation and setup. Install Docker by following the instructions in the official Docker documentation, and start your Docker environment.

Getting started

The fastest way to work through this guide is to clone the Git repository and use the projects that are provided inside:

git clone https://github.com/openliberty/guide-mongodb-intro.git
cd guide-mongodb-intro

The start directory contains the starting project that you will build upon.

The finish directory contains the finished project that you will build.

Before you begin, make sure you have all the necessary prerequisites.

Setting up MongoDB

This guide uses Docker to run an instance of MongoDB. A multi-stage Dockerfile is provided for you. This Dockerfile uses the mongo image as the base image of the final stage and gathers the required configuration files. The resulting mongo image runs in a Docker container, and you must set up a new database for the microservice. Lastly, the truststore that’s generated in the Docker image is copied from the container and placed into the Open Liberty configuration.

You can find more details and configuration options on the MongoDB website. For more information about the mongo image, see mongo in Docker Hub.

Running MongoDB in a Docker container

Run the following commands to use the Dockerfile to build the image, run the image in a Docker container, and map port 27017 from the container to your host machine:

docker build -t mongo-sample -f assets/Dockerfile .
docker run --name mongo-guide -p 27017:27017 -d mongo-sample

Adding the truststore to the Open Liberty configuration

The truststore that’s created in the container needs to be added to the Open Liberty configuration so that the Liberty can trust the certificate that MongoDB presents when they connect. Run the following command to copy the truststore.p12 file from the container to the start and finish directories:

docker cp ^
  mongo-guide:/home/mongodb/certs/truststore.p12 ^
  start/src/main/liberty/config/resources/security
docker cp ^
  mongo-guide:/home/mongodb/certs/truststore.p12 ^
  finish/src/main/liberty/config/resources/security
docker cp \
  mongo-guide:/home/mongodb/certs/truststore.p12 \
  start/src/main/liberty/config/resources/security
docker cp \
  mongo-guide:/home/mongodb/certs/truststore.p12 \
  finish/src/main/liberty/config/resources/security
docker cp \
  mongo-guide:/home/mongodb/certs/truststore.p12 \
  start/src/main/liberty/config/resources/security
docker cp \
  mongo-guide:/home/mongodb/certs/truststore.p12 \
  finish/src/main/liberty/config/resources/security

Try what you’ll build

The finish directory in the root of this guide contains the finished application. Give it a try before you proceed.

To try out the application, first go to the finish directory and run the following Maven goal to build the application and deploy it to Open Liberty:

cd finish
mvn liberty:run

After you see the following message, your Liberty instance is ready:

The defaultServer server is ready to run a smarter planet.

You can now check out the service by going to the http://localhost:9080/mongo/ URL.

After you are finished checking out the application, stop the Liberty instance by pressing CTRL+C in the command-line session where you ran Liberty. Alternatively, you can run the liberty:stop goal from the finish directory in another shell session:

mvn liberty:stop

Providing a MongoDatabase

Navigate to the start directory to begin.

When you run Open Liberty in dev mode, dev mode listens for file changes and automatically recompiles and deploys your updates whenever you save a new change. Run the following goal to start Open Liberty in dev mode:

mvn liberty:dev

After you see the following message, your Liberty instance is ready in dev mode:

**************************************************************
*    Liberty is running in dev mode.

Dev mode holds your command-line session to listen for file changes. Open another command-line session to continue, or open the project in your editor.

With a CDI producer, you can easily provide a MongoDatabase to your microservice.

Create the MongoProducer class.
src/main/java/io/openliberty/guides/mongo/MongoProducer.java

MongoProducer.java

  1// tag::copyright[]
  2/*******************************************************************************
  3 * Copyright (c) 2020, 2024 IBM Corporation and others.
  4 * All rights reserved. This program and the accompanying materials
  5 * are made available under the terms of the Eclipse Public License 2.0
  6 * which accompanies this distribution, and is available at
  7 * http://www.eclipse.org/legal/epl-2.0/
  8 *
  9 * SPDX-License-Identifier: EPL-2.0
 10 *******************************************************************************/
 11// end::copyright[]
 12package io.openliberty.guides.mongo;
 13
 14import java.util.Collections;
 15
 16import javax.net.ssl.SSLContext;
 17
 18import org.eclipse.microprofile.config.inject.ConfigProperty;
 19
 20import com.ibm.websphere.crypto.PasswordUtil;
 21import com.ibm.websphere.ssl.JSSEHelper;
 22import com.ibm.websphere.ssl.SSLException;
 23import com.mongodb.ConnectionString;
 24import com.mongodb.MongoClientSettings;
 25import com.mongodb.MongoCredential;
 26import com.mongodb.client.MongoClient;
 27import com.mongodb.client.MongoClients;
 28import com.mongodb.client.MongoDatabase;
 29
 30import jakarta.enterprise.context.ApplicationScoped;
 31import jakarta.enterprise.inject.Disposes;
 32import jakarta.enterprise.inject.Produces;
 33import jakarta.inject.Inject;
 34
 35@ApplicationScoped
 36public class MongoProducer {
 37
 38    // tag::mongoProducerInjections[]
 39    @Inject
 40    @ConfigProperty(name = "mongo.hostname", defaultValue = "localhost")
 41    String hostname;
 42
 43    @Inject
 44    @ConfigProperty(name = "mongo.port", defaultValue = "27017")
 45    int port;
 46
 47    @Inject
 48    @ConfigProperty(name = "mongo.dbname", defaultValue = "testdb")
 49    String dbName;
 50
 51    @Inject
 52    @ConfigProperty(name = "mongo.user")
 53    String user;
 54
 55    @Inject
 56    @ConfigProperty(name = "mongo.pass.encoded")
 57    String encodedPass;
 58    // end::mongoProducerInjections[]
 59
 60    // tag::produces1[]
 61    @Produces
 62    // end::produces1[]
 63    // tag::createMongo[]
 64    public MongoClient createMongo() throws SSLException {
 65        // tag::decode[]
 66        String password = PasswordUtil.passwordDecode(encodedPass);
 67        // end::decode[]
 68        // tag::createCredential[]
 69        MongoCredential creds = MongoCredential.createCredential(
 70                user,
 71                dbName,
 72                password.toCharArray()
 73        );
 74        // end::createCredential[]
 75
 76        // tag::sslContext[]
 77        SSLContext sslContext = JSSEHelper.getInstance().getSSLContext(
 78                // tag::outboundSSLContext[]
 79                "outboundSSLContext",
 80                // end::outboundSSLContext[]
 81                Collections.emptyMap(),
 82                null
 83        );
 84        // end::sslContext[]
 85
 86        // tag::mongoClient[]
 87        return MongoClients.create(MongoClientSettings.builder()
 88                   .applyConnectionString(
 89                       new ConnectionString("mongodb://" + hostname + ":" + port))
 90                   .credential(creds)
 91                   .applyToSslSettings(builder -> {
 92                       builder.enabled(true);
 93                       builder.context(sslContext); })
 94                   .build());
 95        // end::mongoClient[]
 96    }
 97    // end::createMongo[]
 98
 99    // tag::produces2[]
100    @Produces
101    // end::produces2[]
102    // tag::createDB[]
103    public MongoDatabase createDB(
104            // tag::injectMongoClient[]
105            MongoClient client) {
106            // end::injectMongoClient[]
107        // tag::getDatabase[]
108        return client.getDatabase(dbName);
109        // end::getDatabase[]
110    }
111    // end::createDB[]
112
113    // tag::close[]
114    public void close(
115            // tag::disposes[]
116            @Disposes MongoClient toClose) {
117            // end::disposes[]
118        // tag::toClose[]
119        toClose.close();
120        // end::toClose[]
121    }
122    // end::close[]
123}

microprofile-config.properties

 1# tag::hostname[]
 2mongo.hostname=localhost
 3# end::hostname[]
 4# tag::port[]
 5mongo.port=27017
 6# end::port[]
 7# tag::dbname[]
 8mongo.dbname=testdb
 9# end::dbname[]
10# tag::mongoUser[]
11mongo.user=sampleUser
12# end::mongoUser[]
13# tag::passEncoded[]
14mongo.pass.encoded={aes}APtt+/vYxxPa0jE1rhmZue9wBm3JGqFK3JR4oJdSDGWM1wLr1ckvqkqKjSB2Voty8g==
15# tag::passEncoded[]

pom.xml

  1<?xml version="1.0" encoding="UTF-8"?>
  2<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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  3
  4    <modelVersion>4.0.0</modelVersion>
  5
  6    <groupId>io.openliberty.guides</groupId>
  7    <artifactId>guide-mongodb-intro</artifactId>
  8    <version>1.0-SNAPSHOT</version>
  9    <packaging>war</packaging>
 10
 11    <properties>
 12        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
 13        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
 14        <maven.compiler.source>11</maven.compiler.source>
 15        <maven.compiler.target>11</maven.compiler.target>
 16        <!-- OpenLiberty runtime -->
 17        <version.openliberty-runtime>RELEASE</version.openliberty-runtime>
 18        <!-- tag::defaultHttpPort[] -->
 19        <liberty.var.http.port>9080</liberty.var.http.port>
 20        <!-- end::defaultHttpPort[] -->
 21        <!-- tag::defaultHttpsPort[] -->
 22        <liberty.var.https.port>9443</liberty.var.https.port>
 23        <!-- end::defaultHttpsPort[] -->
 24        <app.name>${project.artifactId}</app.name>
 25        <!-- tag::appContextRoot[] -->
 26        <liberty.var.app.context.root>/mongo</liberty.var.app.context.root>
 27        <!-- end::appContextRoot[] -->
 28        <package.file>${project.build.directory}/${app.name}.zip</package.file>
 29    </properties>
 30
 31    <dependencies>
 32        <!-- Provided dependencies -->
 33        <dependency>
 34            <groupId>jakarta.platform</groupId>
 35            <artifactId>jakarta.jakartaee-api</artifactId>
 36            <version>10.0.0</version>
 37            <scope>provided</scope>
 38        </dependency>
 39        <dependency>
 40            <groupId>org.eclipse.microprofile</groupId>
 41            <artifactId>microprofile</artifactId>
 42            <version>6.1</version>
 43            <type>pom</type>
 44            <scope>provided</scope>
 45        </dependency>
 46        <dependency>
 47            <groupId>javax.validation</groupId>
 48            <artifactId>validation-api</artifactId>
 49            <version>2.0.1.Final</version>
 50            <scope>provided</scope>
 51        </dependency>
 52        <!-- tag::passwordUtilDependency[] -->
 53        <dependency>
 54            <groupId>com.ibm.websphere.appserver.api</groupId>
 55            <artifactId>com.ibm.websphere.appserver.api.passwordUtil</artifactId>
 56            <version>1.0.86</version>
 57            <scope>provided</scope>
 58        </dependency>
 59        <!-- end::passwordUtilDependency[] -->
 60        <!-- tag::sslDependency[] -->
 61        <dependency>
 62            <groupId>com.ibm.websphere.appserver.api</groupId>
 63            <artifactId>com.ibm.websphere.appserver.api.ssl</artifactId>
 64            <version>1.6.86</version>
 65            <scope>provided</scope>
 66        </dependency>
 67        <!-- end::sslDependency[] -->
 68        <!-- Required dependencies -->
 69        <!-- tag::mongoDriver[] -->
 70        <dependency>
 71            <groupId>org.mongodb</groupId>
 72            <artifactId>mongodb-driver-sync</artifactId>
 73            <version>5.0.0</version>
 74        </dependency>
 75        <!-- end::mongoDriver[] -->
 76        <!-- For tests -->
 77        <dependency>
 78            <groupId>org.jboss.resteasy</groupId>
 79            <artifactId>resteasy-client</artifactId>
 80            <version>6.2.7.Final</version>
 81            <scope>test</scope>
 82        </dependency>
 83        <dependency>
 84            <groupId>org.jboss.resteasy</groupId>
 85            <artifactId>resteasy-json-binding-provider</artifactId>
 86            <version>6.2.7.Final</version>
 87            <scope>test</scope>
 88        </dependency>
 89        <dependency>
 90            <groupId>org.glassfish</groupId>
 91            <artifactId>jakarta.json</artifactId>
 92            <version>2.0.1</version>
 93            <scope>test</scope>
 94        </dependency>
 95        <dependency>
 96            <groupId>org.junit.jupiter</groupId>
 97            <artifactId>junit-jupiter</artifactId>
 98            <version>5.10.2</version>
 99            <scope>test</scope>
100        </dependency>
101        <dependency>
102            <groupId>javax.xml.bind</groupId>
103            <artifactId>jaxb-api</artifactId>
104            <version>2.3.1</version>
105            <scope>test</scope>
106        </dependency>
107    </dependencies>
108
109    <build>
110        <defaultGoal>clean package liberty:run-server</defaultGoal>
111        <finalName>${project.artifactId}</finalName>
112        <plugins>
113            <plugin>
114                <groupId>org.apache.maven.plugins</groupId>
115                <artifactId>maven-war-plugin</artifactId>
116                <version>3.4.0</version>
117            </plugin>
118            <!-- Enable liberty-maven plugin -->
119            <plugin>
120                <groupId>io.openliberty.tools</groupId>
121                <artifactId>liberty-maven-plugin</artifactId>
122                <version>3.10.1</version>
123            </plugin>
124            <!-- Plugin to run unit tests -->
125            <plugin>
126                <groupId>org.apache.maven.plugins</groupId>
127                <artifactId>maven-surefire-plugin</artifactId>
128                <version>3.2.5</version>
129            </plugin>
130            <!-- Plugin to run functional tests -->
131            <plugin>
132                <groupId>org.apache.maven.plugins</groupId>
133                <artifactId>maven-failsafe-plugin</artifactId>
134                <version>3.2.5</version>
135                <configuration>
136                    <!-- tag::testsysprops[] -->
137                    <systemPropertyVariables>
138                        <app.http.port>${liberty.var.http.port}</app.http.port>
139                        <app.context.root>${liberty.var.app.context.root}</app.context.root>
140                    </systemPropertyVariables>
141                    <!-- end::testsysprops[] -->
142                </configuration>
143            </plugin>
144        </plugins>
145    </build>
146</project>

server.xml

 1<server description="Sample Liberty server">
 2    <!-- tag::featureManager[] -->
 3    <featureManager>
 4        <!-- tag::cdiFeature[] -->
 5        <feature>cdi-4.0</feature>
 6        <!-- end::cdiFeature[] -->
 7        <!-- tag::sslFeature[] -->
 8        <feature>ssl-1.0</feature>
 9        <!-- end::sslFeature[] -->
10        <!-- tag::mpConfigFeature[] -->
11        <feature>mpConfig-3.1</feature>
12        <!-- end::mpConfigFeature[] -->
13        <!-- tag::passwordUtilFeature[] -->
14        <feature>passwordUtilities-1.1</feature>
15        <!-- end::passwordUtilFeature[] -->
16        <feature>beanValidation-3.0</feature>           
17        <feature>restfulWS-3.1</feature>
18        <feature>jsonb-3.0</feature>
19        <feature>mpOpenAPI-3.1</feature>
20    </featureManager>
21    <!-- end::featureManager[] -->
22
23    <variable name="http.port" defaultValue="9080"/>
24    <variable name="https.port" defaultValue="9443"/>
25    <variable name="app.context.root" defaultValue="/mongo"/>
26
27    <!-- tag::httpEndpoint[] -->
28    <httpEndpoint
29        host="*" 
30        httpPort="${http.port}" 
31        httpsPort="${https.port}" 
32        id="defaultHttpEndpoint"
33    />
34    <!-- end::httpEndpoint[] -->
35
36    <!-- tag::webApplication[] -->
37    <webApplication 
38        location="guide-mongodb-intro.war" 
39        contextRoot="${app.context.root}"
40    />
41    <!-- end::webApplication[] -->
42    <!-- tag::sslContext[] -->
43    <!-- tag::keyStore[] -->
44    <keyStore
45        id="outboundTrustStore" 
46        location="${server.output.dir}/resources/security/truststore.p12"
47        password="mongodb"
48        type="PKCS12" 
49    />
50    <!-- end::keyStore[] -->
51    <!-- tag::ssl[] -->
52    <ssl 
53        id="outboundSSLContext" 
54        keyStoreRef="defaultKeyStore" 
55        trustStoreRef="outboundTrustStore" 
56        sslProtocol="TLS" 
57    />
58    <!-- end::ssl[] -->
59    <!-- end::sslContext[] -->
60</server>

The values from the microprofile-config.properties file are injected into the MongoProducer class. The MongoProducer class requires the following methods for the MongoClient:

  • The createMongo() producer method returns an instance of MongoClient. In this method, the username, database name, and decoded password are passed into the MongoCredential.createCredential() method to get an instance of MongoCredential. The JSSEHelper gets the SSLContext from the outboundSSLContext in the server.xml configuration file. Then, a MongoClient instance is created.

  • The createDB() producer method returns an instance of MongoDatabase that depends on the MongoClient. This method injects the MongoClient in its parameters and passes the database name into the MongoClient.getDatabase() method to get a MongoDatabase instance.

  • The close() method is a clean-up function for the MongoClient that closes the connection to the MongoDatabase instance.

Implementing the Create, Retrieve, Update, and Delete operations

You are going to implement the basic create, retrieve, update, and delete (CRUD) operations in the CrewService class. The com.mongodb.client and com.mongodb.client.result packages are used to help implement these operations for the microservice. For more information about these packages, see the com.mongodb.client and com.mongodb.client.result Javadoc. For more information about creating a RESTful service with JAX-RS, JSON-B, and Open Liberty, see the guide on Creating a RESTful web serivce.

Create the CrewService class.
src/main/java/io/openliberty/guides/application/CrewService.java

CrewService.java

  1// tag::copyright[]
  2/*******************************************************************************
  3 * Copyright (c) 2020, 2022 IBM Corporation and others.
  4 * All rights reserved. This program and the accompanying materials
  5 * are made available under the terms of the Eclipse Public License 2.0
  6 * which accompanies this distribution, and is available at
  7 * http://www.eclipse.org/legal/epl-2.0/
  8 *
  9 * SPDX-License-Identifier: EPL-2.0
 10 *******************************************************************************/
 11// end::copyright[]
 12package io.openliberty.guides.application;
 13
 14import java.util.Set;
 15
 16import java.io.StringWriter;
 17
 18import jakarta.enterprise.context.ApplicationScoped;
 19import jakarta.inject.Inject;
 20import jakarta.json.JsonArray;
 21import jakarta.json.JsonArrayBuilder;
 22import jakarta.json.Json;
 23import jakarta.ws.rs.GET;
 24import jakarta.ws.rs.POST;
 25import jakarta.ws.rs.PUT;
 26import jakarta.ws.rs.Path;
 27import jakarta.ws.rs.Consumes;
 28import jakarta.ws.rs.DELETE;
 29import jakarta.ws.rs.Produces;
 30import jakarta.ws.rs.PathParam;
 31import jakarta.ws.rs.core.MediaType;
 32import jakarta.ws.rs.core.Response;
 33
 34import jakarta.validation.Validator;
 35import jakarta.validation.ConstraintViolation;
 36
 37import com.mongodb.client.FindIterable;
 38// tag::bsonDocument[]
 39import org.bson.Document;
 40// end::bsonDocument[]
 41import org.bson.types.ObjectId;
 42
 43// tag::mongoImports1[]
 44import com.mongodb.client.MongoCollection;
 45import com.mongodb.client.MongoDatabase;
 46// end::mongoImports1[]
 47// tag::mongoImports2[]
 48import com.mongodb.client.result.DeleteResult;
 49import com.mongodb.client.result.UpdateResult;
 50// end::mongoImports2[]
 51
 52import org.eclipse.microprofile.openapi.annotations.Operation;
 53import org.eclipse.microprofile.openapi.annotations.parameters.Parameter;
 54import org.eclipse.microprofile.openapi.annotations.responses.APIResponse;
 55import org.eclipse.microprofile.openapi.annotations.responses.APIResponses;
 56
 57@Path("/crew")
 58@ApplicationScoped
 59public class CrewService {
 60
 61    // tag::dbInjection[]
 62    @Inject
 63    MongoDatabase db;
 64    // end::dbInjection[]
 65
 66    // tag::beanValidator[]
 67    @Inject
 68    Validator validator;
 69    // end::beanValidator[]
 70
 71    // tag::getViolations[]
 72    private JsonArray getViolations(CrewMember crewMember) {
 73        Set<ConstraintViolation<CrewMember>> violations = validator.validate(
 74                crewMember);
 75
 76        JsonArrayBuilder messages = Json.createArrayBuilder();
 77
 78        for (ConstraintViolation<CrewMember> v : violations) {
 79            messages.add(v.getMessage());
 80        }
 81
 82        return messages.build();
 83    }
 84    // end::getViolations[]
 85
 86    @POST
 87    @Path("/")
 88    @Consumes(MediaType.APPLICATION_JSON)
 89    @Produces(MediaType.APPLICATION_JSON)
 90    @APIResponses({
 91        @APIResponse(
 92            responseCode = "200",
 93            description = "Successfully added crew member."),
 94        @APIResponse(
 95            responseCode = "400",
 96            description = "Invalid crew member configuration.") })
 97    @Operation(summary = "Add a new crew member to the database.")
 98    // tag::add[]
 99    public Response add(CrewMember crewMember) {
100        JsonArray violations = getViolations(crewMember);
101
102        if (!violations.isEmpty()) {
103            return Response
104                    .status(Response.Status.BAD_REQUEST)
105                    .entity(violations.toString())
106                    .build();
107        }
108
109        // tag::getCollection[]
110        MongoCollection<Document> crew = db.getCollection("Crew");
111        // end::getCollection[]
112
113        // tag::crewMemberCreation[]
114        Document newCrewMember = new Document();
115        newCrewMember.put("Name", crewMember.getName());
116        newCrewMember.put("Rank", crewMember.getRank());
117        newCrewMember.put("CrewID", crewMember.getCrewID());
118        // end::crewMemberCreation[]
119
120        // tag::insertOne[]
121        crew.insertOne(newCrewMember);
122        // end::insertOne[]
123
124        return Response
125            .status(Response.Status.OK)
126            .entity(newCrewMember.toJson())
127            .build();
128    }
129    // end::add[]
130
131    @GET
132    @Path("/")
133    @Produces(MediaType.APPLICATION_JSON)
134    @APIResponses({
135        @APIResponse(
136            responseCode = "200",
137            description = "Successfully listed the crew members."),
138        @APIResponse(
139            responseCode = "500",
140            description = "Failed to list the crew members.") })
141    @Operation(summary = "List the crew members from the database.")
142    // tag::retrieve[]
143    public Response retrieve() {
144        StringWriter sb = new StringWriter();
145
146        try {
147            // tag::getCollectionRead[]
148            MongoCollection<Document> crew = db.getCollection("Crew");
149            // end::getCollectionRead[]
150            sb.append("[");
151            boolean first = true;
152            // tag::find[]
153            FindIterable<Document> docs = crew.find();
154            // end::find[]
155            for (Document d : docs) {
156                if (!first) {
157                    sb.append(",");
158                } else {
159                    first = false;
160                }
161                sb.append(d.toJson());
162            }
163            sb.append("]");
164        } catch (Exception e) {
165            e.printStackTrace(System.out);
166            return Response
167                .status(Response.Status.INTERNAL_SERVER_ERROR)
168                .entity("[\"Unable to list crew members!\"]")
169                .build();
170        }
171
172        return Response
173            .status(Response.Status.OK)
174            .entity(sb.toString())
175            .build();
176    }
177    // end::retrieve[]
178
179    @PUT
180    @Path("/{id}")
181    @Consumes(MediaType.APPLICATION_JSON)
182    @Produces(MediaType.APPLICATION_JSON)
183    @APIResponses({
184        @APIResponse(
185            responseCode = "200",
186            description = "Successfully updated crew member."),
187        @APIResponse(
188            responseCode = "400",
189            description = "Invalid object id or crew member configuration."),
190        @APIResponse(
191            responseCode = "404",
192            description = "Crew member object id was not found.") })
193    @Operation(summary = "Update a crew member in the database.")
194    // tag::update[]
195    public Response update(CrewMember crewMember,
196        @Parameter(
197            description = "Object id of the crew member to update.",
198            required = true
199        )
200        @PathParam("id") String id) {
201
202        JsonArray violations = getViolations(crewMember);
203
204        if (!violations.isEmpty()) {
205            return Response
206                    .status(Response.Status.BAD_REQUEST)
207                    .entity(violations.toString())
208                    .build();
209        }
210
211        ObjectId oid;
212
213        try {
214            oid = new ObjectId(id);
215        } catch (Exception e) {
216            return Response
217                .status(Response.Status.BAD_REQUEST)
218                .entity("[\"Invalid object id!\"]")
219                .build();
220        }
221
222        // tag::getCollectionUpdate[]
223        MongoCollection<Document> crew = db.getCollection("Crew");
224        // end::getCollectionUpdate[]
225
226        // tag::queryUpdate[]
227        Document query = new Document("_id", oid);
228        // end::queryUpdate[]
229
230        // tag::crewMemberUpdate[]
231        Document newCrewMember = new Document();
232        newCrewMember.put("Name", crewMember.getName());
233        newCrewMember.put("Rank", crewMember.getRank());
234        newCrewMember.put("CrewID", crewMember.getCrewID());
235        // end::crewMemberUpdate[]
236
237        // tag::replaceOne[]
238        UpdateResult updateResult = crew.replaceOne(query, newCrewMember);
239        // end::replaceOne[]
240
241        // tag::getMatchedCount[]
242        if (updateResult.getMatchedCount() == 0) {
243        // end::getMatchedCount[]
244            return Response
245                .status(Response.Status.NOT_FOUND)
246                .entity("[\"_id was not found!\"]")
247                .build();
248        }
249
250        newCrewMember.put("_id", oid);
251
252        return Response
253            .status(Response.Status.OK)
254            .entity(newCrewMember.toJson())
255            .build();
256    }
257    // end::update[]
258
259    @DELETE
260    @Path("/{id}")
261    @Produces(MediaType.APPLICATION_JSON)
262    @APIResponses({
263        @APIResponse(
264            responseCode = "200",
265            description = "Successfully deleted crew member."),
266        @APIResponse(
267            responseCode = "400",
268            description = "Invalid object id."),
269        @APIResponse(
270            responseCode = "404",
271            description = "Crew member object id was not found.") })
272    @Operation(summary = "Delete a crew member from the database.")
273    // tag::remove[]
274    public Response remove(
275        @Parameter(
276            description = "Object id of the crew member to delete.",
277            required = true
278        )
279        @PathParam("id") String id) {
280
281        ObjectId oid;
282
283        try {
284            oid = new ObjectId(id);
285        } catch (Exception e) {
286            return Response
287                .status(Response.Status.BAD_REQUEST)
288                .entity("[\"Invalid object id!\"]")
289                .build();
290        }
291
292        // tag::getCollectionDelete[]
293        MongoCollection<Document> crew = db.getCollection("Crew");
294        // end::getCollectionDelete[]
295
296        // tag::queryDelete[]
297        Document query = new Document("_id", oid);
298        // end::queryDelete[]
299
300        // tag::deleteOne[]
301        DeleteResult deleteResult = crew.deleteOne(query);
302        // end::deleteOne[]
303
304        // tag::getDeletedCount[]
305        if (deleteResult.getDeletedCount() == 0) {
306        // end::getDeletedCount[]
307            return Response
308                .status(Response.Status.NOT_FOUND)
309                .entity("[\"_id was not found!\"]")
310                .build();
311        }
312
313        return Response
314            .status(Response.Status.OK)
315            .entity(query.toJson())
316            .build();
317    }
318    // end::remove[]
319}

CrewMember.java

 1// tag::copyright[]
 2/*******************************************************************************
 3 * Copyright (c) 2020, 2022 IBM Corporation and others.
 4 * All rights reserved. This program and the accompanying materials
 5 * are made available under the terms of the Eclipse Public License 2.0
 6 * which accompanies this distribution, and is available at
 7 * http://www.eclipse.org/legal/epl-2.0/
 8 *
 9 * SPDX-License-Identifier: EPL-2.0
10 *******************************************************************************/
11// end::copyright[]
12package io.openliberty.guides.application;
13
14import jakarta.validation.constraints.NotEmpty;
15import jakarta.validation.constraints.Pattern;
16
17// tag::crewMember[]
18public class CrewMember {
19
20    @NotEmpty(message = "All crew members must have a name!")
21    private String name;
22
23    @Pattern(regexp = "(Captain|Officer|Engineer)",
24            message = "Crew member must be one of the listed ranks!")
25    private String rank;
26
27    @Pattern(regexp = "^\\d+$",
28            message = "ID Number must be a non-negative integer!")
29    private String crewID;
30
31    public String getName() {
32        return name;
33    }
34
35    public void setName(String name) {
36        this.name = name;
37    }
38
39    public String getRank() {
40        return rank;
41    }
42
43    public void setRank(String rank) {
44        this.rank = rank;
45    }
46
47    public String getCrewID() {
48        return crewID;
49    }
50
51    public void setCrewID(String crewID) {
52        this.crewID = crewID;
53    }
54
55}
56// end::crewMember[]

In this class, a Validator is used to validate a CrewMember before the database is updated. The CDI producer is used to inject a MongoDatabase into the CrewService class.

Implementing the Create operation

The add() method handles the implementation of the create operation. An instance of MongoCollection is retrieved with the MongoDatabase.getCollection() method. The Document type parameter specifies that the Document type is used to store data in the MongoCollection. Each crew member is converted into a Document, and the MongoCollection.insertOne() method inserts a new crew member document.

Implementing the Retrieve operation

The retrieve() method handles the implementation of the retrieve operation. The Crew collection is retrieved with the MongoDatabase.getCollection() method. Then, the MongoCollection.find() method retrieves a FindIterable object. This object is iterable for all the crew members documents in the collection, so each crew member document is concatenated into a String array and returned.

Implementing the Update operation

The update() method handles the implementation of the update operation. After the Crew collection is retrieved, a document is created with the specified object id and is used to query the collection. Next, a new crew member Document is created with the updated configuration. The MongoCollection.replaceOne() method is called with the query and new crew member document. This method updates all of the matching queries with the new document. Because the object id is unique in the Crew collection, only one document is updated. The MongoCollection.replaceOne() method also returns an UpdateResult instance, which determines how many documents matched the query. If there are zero matches, then the object id doesn’t exist.

Implementing the Delete operation

The remove() method handles the implementation of the delete operation. After the Crew collection is retrieved, a Document is created with the specified object id and is used to query the collection. Because the object id is unique in the Crew collection, only one document is deleted. After the document is deleted, the MongoCollection.deleteOne() method returns a DeleteResult instance, which determines how many documents were deleted. If zero documents were deleted, then the object id doesn’t exist.

Configuring the MongoDB driver and the Liberty

MicroProfile Config makes configuring the MongoDB driver simple because all of the configuration can be set in one place and injected into the CDI producer.

Create the configuration file.
src/main/webapp/META-INF/microprofile-config.properties

microprofile-config.properties

 1# tag::hostname[]
 2mongo.hostname=localhost
 3# end::hostname[]
 4# tag::port[]
 5mongo.port=27017
 6# end::port[]
 7# tag::dbname[]
 8mongo.dbname=testdb
 9# end::dbname[]
10# tag::mongoUser[]
11mongo.user=sampleUser
12# end::mongoUser[]
13# tag::passEncoded[]
14mongo.pass.encoded={aes}APtt+/vYxxPa0jE1rhmZue9wBm3JGqFK3JR4oJdSDGWM1wLr1ckvqkqKjSB2Voty8g==
15# tag::passEncoded[]

Values such as the hostname, port, and database name for the running MongoDB instance are set in this file. The user’s username and password are also set here. For added security, the password was encoded by using the securityUtility encode command.

To create a CDI producer for MongoDB and connect over TLS, the Open Liberty needs to be correctly configured.

Replace the Liberty server.xml configuration file.
src/main/liberty/config/server.xml

server.xml

 1<server description="Sample Liberty server">
 2    <!-- tag::featureManager[] -->
 3    <featureManager>
 4        <!-- tag::cdiFeature[] -->
 5        <feature>cdi-4.0</feature>
 6        <!-- end::cdiFeature[] -->
 7        <!-- tag::sslFeature[] -->
 8        <feature>ssl-1.0</feature>
 9        <!-- end::sslFeature[] -->
10        <!-- tag::mpConfigFeature[] -->
11        <feature>mpConfig-3.1</feature>
12        <!-- end::mpConfigFeature[] -->
13        <!-- tag::passwordUtilFeature[] -->
14        <feature>passwordUtilities-1.1</feature>
15        <!-- end::passwordUtilFeature[] -->
16        <feature>beanValidation-3.0</feature>           
17        <feature>restfulWS-3.1</feature>
18        <feature>jsonb-3.0</feature>
19        <feature>mpOpenAPI-3.1</feature>
20    </featureManager>
21    <!-- end::featureManager[] -->
22
23    <variable name="http.port" defaultValue="9080"/>
24    <variable name="https.port" defaultValue="9443"/>
25    <variable name="app.context.root" defaultValue="/mongo"/>
26
27    <!-- tag::httpEndpoint[] -->
28    <httpEndpoint
29        host="*" 
30        httpPort="${http.port}" 
31        httpsPort="${https.port}" 
32        id="defaultHttpEndpoint"
33    />
34    <!-- end::httpEndpoint[] -->
35
36    <!-- tag::webApplication[] -->
37    <webApplication 
38        location="guide-mongodb-intro.war" 
39        contextRoot="${app.context.root}"
40    />
41    <!-- end::webApplication[] -->
42    <!-- tag::sslContext[] -->
43    <!-- tag::keyStore[] -->
44    <keyStore
45        id="outboundTrustStore" 
46        location="${server.output.dir}/resources/security/truststore.p12"
47        password="mongodb"
48        type="PKCS12" 
49    />
50    <!-- end::keyStore[] -->
51    <!-- tag::ssl[] -->
52    <ssl 
53        id="outboundSSLContext" 
54        keyStoreRef="defaultKeyStore" 
55        trustStoreRef="outboundTrustStore" 
56        sslProtocol="TLS" 
57    />
58    <!-- end::ssl[] -->
59    <!-- end::sslContext[] -->
60</server>

The features that are required to create the CDI producer for MongoDB are Contexts and Dependency Injection (cdi-4.0), Secure Socket Layer (ssl-1.0), MicroProfile Config (mpConfig-3.0), and Password Utilities (passwordUtilities-1.1). These features are specified in the featureManager element. The Secure Socket Layer (SSL) context is configured in the server.xml configuration file so that the application can connect to MongoDB with TLS. The keyStore element points to the truststore.p12 keystore file that was created in one of the previous sections. The ssl element specifies the defaultKeyStore as the keystore and outboundTrustStore as the truststore.

After you replace the server.xml file, the Open Liberty configuration is automatically reloaded.

Running the application

You started the Open Liberty in dev mode at the beginning of the guide, so all the changes were automatically picked up.

Go to the http://localhost:9080/openapi/ui/ URL to see the OpenAPI user interface (UI) that provides API documentation and a client to test the API endpoints that you create after you see a message similar to the following example:

CWWKZ0001I: Application guide-mongodb-intro started in 5.715 seconds.

Try the Create operation

From the OpenAPI UI, test the create operation at the POST /api/crew endpoint by using the following code as the request body:

{
  "name": "Member1",
  "rank": "Officer",
  "crewID": "000001"
}

This request creates a new document in the Crew collection with a name of Member1, rank of Officer, and crew ID of 000001.

You’ll receive a response that contains the JSON object of the new crew member, as shown in the following example:

{
  "Name": "Member1",
  "Rank": "Officer",
  "CrewID": "000001",
  "_id": {
    "$oid": "<<ID>>"
  }
}

The <<ID>> that you receive is a unique identifier in the collection. Save this value for future commands.

Try the Retrieve operation

From the OpenAPI UI, test the read operation at the GET /api/crew endpoint. This request gets all crew member documents from the collection.

You’ll receive a response that contains an array of all the members in your crew. The response might include crew members that were created in the Try what you’ll build section of this guide:

[
  {
    "_id": {
      "$oid": "<<ID>>"
    },
    "Name": "Member1",
    "Rank": "Officer",
    "CrewID": "000001"
  }
]

Try the Update operation

From the OpenAPI UI, test the update operation at the PUT /api/crew/{id} endpoint, where the {id} parameter is the <<ID>> that you saved from the create operation. Use the following code as the request body:

{
  "name": "Member1",
  "rank": "Captain",
  "crewID": "000001"
}

This request updates the rank of the crew member that you created from Officer to Captain.

You’ll receive a response that contains the JSON object of the updated crew member, as shown in the following example:

{
  "Name": "Member1",
  "Rank": "Captain",
  "CrewID": "000001",
  "_id": {
    "$oid": "<<ID>>"
  }
}

Try the Delete operation

From the OpenAPI UI, test the delete operation at the DELETE/api/crew/{id} endpoint, where the {id} parameter is the <<ID>> that you saved from the create operation. This request removes the document that contains the specified crew member object id from the collection.

You’ll receive a response that contains the object id of the deleted crew member, as shown in the following example:

{
  "_id": {
    "$oid": "<<ID>>"
  }
}

Now, you can check out the microservice that you created by going to the http://localhost:9080/mongo/ URL.

Testing the application

Next, you’ll create integration tests to ensure that the basic operations you implemented function correctly.

Create the CrewServiceIT class.
src/test/java/it/io/openliberty/guides/application/CrewServiceIT.java

CrewServiceIT.java

  1// tag::copyright[]
  2/*******************************************************************************
  3 * Copyright (c) 2020, 2022 IBM Corporation and others.
  4 * All rights reserved. This program and the accompanying materials
  5 * are made available under the terms of the Eclipse Public License 2.0
  6 * which accompanies this distribution, and is available at
  7 * http://www.eclipse.org/legal/epl-2.0/
  8 *
  9 * SPDX-License-Identifier: EPL-2.0
 10 *******************************************************************************/
 11// end::copyright[]
 12package it.io.openliberty.guides.application;
 13
 14import static org.junit.jupiter.api.Assertions.assertEquals;
 15
 16import java.io.StringReader;
 17import java.util.ArrayList;
 18
 19import org.junit.jupiter.api.AfterAll;
 20import org.junit.jupiter.api.BeforeAll;
 21import org.junit.jupiter.api.Order;
 22import org.junit.jupiter.api.Test;
 23import org.junit.jupiter.api.MethodOrderer;
 24import org.junit.jupiter.api.TestMethodOrder;
 25
 26import jakarta.json.Json;
 27import jakarta.json.JsonArray;
 28import jakarta.json.JsonArrayBuilder;
 29import jakarta.json.JsonObject;
 30import jakarta.json.JsonObjectBuilder;
 31import jakarta.json.JsonReader;
 32import jakarta.json.JsonValue;
 33import jakarta.ws.rs.client.Client;
 34import jakarta.ws.rs.client.ClientBuilder;
 35import jakarta.ws.rs.core.Response;
 36import jakarta.ws.rs.client.Entity;
 37
 38@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
 39public class CrewServiceIT {
 40
 41    private static Client client;
 42    private static JsonArray testData;
 43    private static String rootURL;
 44    private static ArrayList<String> testIDs = new ArrayList<>(2);
 45
 46    @BeforeAll
 47    public static void setup() {
 48        client = ClientBuilder.newClient();
 49
 50        String port = System.getProperty("app.http.port");
 51        String context = System.getProperty("app.context.root");
 52        rootURL = "http://localhost:" + port + context;
 53
 54        // test data
 55        JsonArrayBuilder arrayBuilder = Json.createArrayBuilder();
 56        JsonObjectBuilder jsonBuilder = Json.createObjectBuilder();
 57        jsonBuilder.add("name", "Member1");
 58        jsonBuilder.add("crewID", "000001");
 59        jsonBuilder.add("rank", "Captain");
 60        arrayBuilder.add(jsonBuilder.build());
 61        jsonBuilder = Json.createObjectBuilder();
 62        jsonBuilder.add("name", "Member2");
 63        jsonBuilder.add("crewID", "000002");
 64        jsonBuilder.add("rank", "Engineer");
 65        arrayBuilder.add(jsonBuilder.build());
 66        testData = arrayBuilder.build();
 67    }
 68
 69    @AfterAll
 70    public static void teardown() {
 71        client.close();
 72    }
 73
 74    // tag::testAddCrewMember[]
 75    // tag::test1[]
 76    @Test
 77    // end::test1[]
 78    @Order(1)
 79    public void testAddCrewMember() {
 80        System.out.println("   === Adding " + testData.size()
 81                + " crew members to the database. ===");
 82
 83        for (int i = 0; i < testData.size(); i++) {
 84            JsonObject member = (JsonObject) testData.get(i);
 85            String url = rootURL + "/api/crew";
 86            Response response = client.target(url).request().post(Entity.json(member));
 87            this.assertResponse(url, response);
 88
 89            JsonObject newMember = response.readEntity(JsonObject.class);
 90            testIDs.add(newMember.getJsonObject("_id").getString("$oid"));
 91
 92            response.close();
 93        }
 94        System.out.println("      === Done. ===");
 95    }
 96    // end::testAddCrewMember[]
 97
 98    // tag::testUpdateCrewMember[]
 99    // tag::test2[]
100    @Test
101    // end::test2[]
102    @Order(2)
103    public void testUpdateCrewMember() {
104        System.out.println("   === Updating crew member with id " + testIDs.get(0)
105                + ". ===");
106
107        JsonObject oldMember = (JsonObject) testData.get(0);
108
109        JsonObjectBuilder newMember = Json.createObjectBuilder();
110        newMember.add("name", oldMember.get("name"));
111        newMember.add("crewID", oldMember.get("crewID"));
112        newMember.add("rank", "Officer");
113
114        String url = rootURL + "/api/crew/" + testIDs.get(0);
115        Response response = client.target(url).request()
116                .put(Entity.json(newMember.build()));
117
118        this.assertResponse(url, response);
119
120        System.out.println("      === Done. ===");
121    }
122    // end::testUpdateCrewMember[]
123
124    // tag::testGetCrewMembers[]
125    // tag::test3[]
126    @Test
127    // end::test3[]
128    @Order(3)
129    public void testGetCrewMembers() {
130        System.out.println("   === Listing crew members from the database. ===");
131
132        String url = rootURL + "/api/crew";
133        Response response = client.target(url).request().get();
134
135        this.assertResponse(url, response);
136
137        String responseText = response.readEntity(String.class);
138        JsonReader reader = Json.createReader(new StringReader(responseText));
139        JsonArray crew = reader.readArray();
140        reader.close();
141
142        int testMemberCount = 0;
143        for (JsonValue value : crew) {
144            JsonObject member = (JsonObject) value;
145            String id = member.getJsonObject("_id").getString("$oid");
146            if (testIDs.contains(id)) {
147                testMemberCount++;
148            }
149        }
150
151        assertEquals(testIDs.size(), testMemberCount,
152                "Incorrect number of testing members.");
153
154        System.out.println("      === Done. There are " + crew.size()
155                + " crew members. ===");
156
157        response.close();
158    }
159    // end::testGetCrewMembers[]
160
161    // tag::testDeleteCrewMember[]
162    // tag::test4[]
163    @Test
164    // end::test4[]
165    @Order(4)
166    public void testDeleteCrewMember() {
167        System.out.println("   === Removing " + testIDs.size()
168                + " crew members from the database. ===");
169
170        for (String id : testIDs) {
171            String url = rootURL + "/api/crew/" + id;
172            Response response = client.target(url).request().delete();
173            this.assertResponse(url, response);
174            response.close();
175        }
176
177        System.out.println("      === Done. ===");
178    }
179    // end::testDeleteCrewMember[]
180
181    private void assertResponse(String url, Response response) {
182        assertEquals(200, response.getStatus(), "Incorrect response code from " + url);
183    }
184}

The test methods are annotated with the @Test annotation.

The following test cases are included in this class:

  • testAddCrewMember() verifies that new members are correctly added to the database.

  • testUpdateCrewMember() verifies that a crew member’s information is correctly updated.

  • testGetCrewMembers() verifies that a list of crew members is returned by the microservice API.

  • testDeleteCrewMember() verifies that the crew members are correctly removed from the database.

Running the tests

Because you started Open Liberty in dev mode, you can run the tests by pressing the enter/return key from the command-line session where you started dev mode.

You’ll see the following output:

-------------------------------------------------------
 T E S T S
-------------------------------------------------------
Running it.io.openliberty.guides.application.CrewServiceIT
   === Adding 2 crew members to the database. ===
      === Done. ===
   === Updating crew member with id 5df8e0a004ccc019976c7d0a. ===
      === Done. ===
   === Listing crew members from the database. ===
      === Done. There are 2 crew members. ===
   === Removing 2 crew members from the database. ===
      === Done. ===
Tests run: 4, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.411 s - in it.io.openliberty.guides.application.CrewServiceIT
Results:
Tests run: 4, Failures: 0, Errors: 0, Skipped: 0

Tearing down the environment

When you are done checking out the service, exit dev mode by pressing CTRL+C in the command-line session where you ran Liberty.

Then, run the following commands to stop and remove the mongo-guide container and to remove the mongo-sample and mongo images.

docker stop mongo-guide
docker rm mongo-guide
docker rmi mongo-sample

Great work! You’re done!

You’ve successfully accessed and persisted data to a MongoDB database from a Java microservice using Contexts and Dependency Injection (CDI) and MicroProfile Config with Open Liberty.

Learn more about MicroProfile.

Guide Attribution

Persisting data with MongoDB by Open Liberty is licensed under CC BY-ND 4.0

Copy file contents
Copied to clipboard

Prerequisites:

Nice work! Where to next?

What did you think of this guide?

Extreme Dislike Dislike Like Extreme Like

What could make this guide better?

Raise an issue to share feedback

Create a pull request to contribute to this guide

Need help?

Ask a question on Stack Overflow

Like Open Liberty? Star our repo on GitHub.

Star