MongoDB Java CRUD Operations Example Tutorial

MongoDB Java CRUD Operations Example Tutorial

In this tutorial, MongoDB Java CRUD Operations Example Tutorial we will focus on using CRUD Operations (Create, Read, Update and Delete) with the latest version of MongoDB using Java and MongoDB Java Driver (mongo-java-driver-3.2.0.jar). We will focus our efforts on insertOne, updateOne, replaceOne, findOneAndUpdate and findOneAndDelete. In a subsequent tutorial, we will cover the other methods including deleteMany, insertMany, updateMany and bulkWrite.

In our previous tutorial “Java Connecting to MongoDB 3.2 Examples“, we covered how to connect to MongoDB and how to use the newer classes including MongoDatabase, MongoCollection, MongoCursor and how to perform basic inserts using BasicDBObjelist_ct, inserting documents via Maps, and inserting data using JSON.

What’s Covered

  1. Connecting to MongoDB Server using MongoClient
  2. Performing Inserts in MongoDB
  3. MongoWriteException when performing Insert
  4. Using MongoDB 3.2 Upsert Java Examples
  5. Update the Collection using UpdateOne
  6. Seeing the Results of the UpdateOne for Upsert Operation Test
  7. Using MongoDB 3.2 replaceOne Upsert Java Examples
  8. Testing the replaceOne for Upsert Operation
  9. Seeing the Results of the ReplaceOne for Upsert Operation Test
  10. Testing out our MongoDBCrudExample Application

Getting Started

In order to run this tutorial yourself, you will need the following:

Required Libraries

Copy all of the following jars to WebContent->WEB-INF->lib folder.

jackson-core-asl-1.9.13.jar
jackson-mapper-asl-1.9.13.jar
mongo-java-driver-3.2.0.jar

Project Overview

I have added the project overview to give you a full view of the structure and show you all files contained in this sample project.

mongodb_crud_proj_struct

Connecting to MongoDB Server using MongoClient

MongoClient is used to make a connection to MongoDB server. In our example, we use MongoClient to get a database object and connect to the ‘test’ database where we make use of the ‘inventory’ collection.

MongoClient mongoClient = new MongoClient();
MongoDatabase db = mongoClient.getDatabase("test");
MongoCollection<Document> collection = db.getCollection("inventory");

Performing Inserts in MongoDB

In this example, we begin by building our Item object by populating all of the properties using the object’s setter methods. We will use this object in our insert method ‘insertIntoCollection‘. We are using Jackson to convert our object to a JSON string. This JSON string will be parsed using Document.parse(jsonString) and the newly created document will be inserted into the collection using collection.insertOne(doc).

Note:
Please be aware that if you were to run this application a second time or if the document already existed in the collection the insertOne() method would result in a com.mongodb.MongoWriteException duplicate key error. However, I am specifically catching ‘MongoWriteException’ and setting flag to false in the even of such error, to let you know that the operation failed.

MongoWriteException when performing Insert

	com.mongodb.MongoWriteException: E11000 duplicate key error index: test.inventory.$_id_ dup key: { : "1454163351" }
	at com.mongodb.MongoCollectionImpl.executeSingleWriteRequest(MongoCollectionImpl.java:523)
	at com.mongodb.MongoCollectionImpl.insertOne(MongoCollectionImpl.java:306)
	at com.mongodb.MongoCollectionImpl.insertOne(MongoCollectionImpl.java:297)
	at com.avaldes.tutorial.MongoDBCrudExample.insertIntoCollection(MongoDBCrudExample.java:134)
	at com.avaldes.tutorial.MongoDBCrudExample.mongoTestCRUDOperations(MongoDBCrudExample.java:59)
	at com.avaldes.tutorial.MongoDBCrudExample.main(MongoDBCrudExample.java:25)
// Insert Item Java Model into MongoDB
// ---Item #1---
final Item item1 = new Item();
item1.setId("1454163351");
item1.setItemId("B0037ZG3DS");
item1.setDescription("Mr. Coffee BVMC-PSTX91 Optimal Brew...";
item1.setManufacturer("Mr. Coffee");
item1.setDepartment("kitchen");
item1.setCategory("Coffee Machines");
item1.setSubCategory("Thermal Carafe");
item1.setListPrice(89.99);
item1.setPrice(69.00);
item1.setQuantity(3);

boolean status = insertIntoCollection(collection, item1);
System.out.println("Status of Insert: " + status);

public static boolean insertIntoCollection(
	final MongoCollection<Document> collection, final Item item) {
	// Use Jackson to convert Object to JSON String
	ObjectMapper mapper = new ObjectMapper();
	String jsonString;
	boolean status = true;

	try {
		jsonString = mapper.writeValueAsString(item);
		// Insert JSON into MongoDB
		System.out.println(String.format("Item #%s: %s", item.getId(),
				jsonString));
		Document doc = Document.parse(jsonString);
		collection.insertOne(doc);
	} catch (MongoWriteException mwe) {
		status = false;
	} catch (IOException e) {
		status = false;
	}
	return status;
}
mongodb_crud_insert_update

Using MongoDB 3.2 Upsert Java Examples

As you can clearly see from the example above, the insert will only work the first time and any subsequent inserts on the same object would fail quietly. Ideally, you would need to search MongoDB to see if document exists, if it does you would need to perform an update to the record otherwise you can use the insert operation. MongoDB provides an alternative to this by using the Upsert methods.

The MongoDB Upsert Operation is a special type of update which uses the selection criteria for the update. Should the document be found it will perform the update as expected, however, if the document is not found, it will insert a new document into the collection. This makes your code much cleaner and easier to maintain.

Setting the UpdateOptions Upsert Flag

Setting this flag in Java is quite simple: new UpdateOptions()).upsert(true).

UpdateResult result = collection.updateOne(query, newDocument, 
																(new UpdateOptions()).upsert(true));

Update the Collection using UpdateOne

public static boolean updateCollection(
	final MongoCollection<Document> collection, final Item item) {
	boolean status = true;
	ObjectMapper mapper = new ObjectMapper();
	String jsonString;

	try {
		jsonString = mapper.writeValueAsString(item);
		// update/upsert using JSON into MongoDB
		System.out.println(String.format("Item #%s: %s", item.getId(),
				jsonString));
		BasicDBObject query = new BasicDBObject();
		query.append("_id", item.getId());
		BasicDBObject doc = BasicDBObject.parse(jsonString);
		Bson newDocument = new Document("$set", doc);
		UpdateResult result = collection.updateOne(query, newDocument,
				(new UpdateOptions()).upsert(true));
		System.out.println("Update Matched Count....: "
				+ result.getMatchedCount());
		System.out.println("Update Modified Count...: "
				+ result.getModifiedCount());
	} catch (IOException e) {
		status = false;
	}

	return status;
}

Testing the UpdateOne for Upsert Operation

When this method is executed the first time, you will notice that the update matched count is still zero meaning that the record was not found and so it was not updated. Instead MongoDB inserts the document into the collection. You can see that the output from MongoDB verifies that _id=1454163352 was inserted with a price of $29.97 (Line #5). We then change the price from $29.97 to $31.99 and perform another updateCollection with the updated item object. This time the document was found in MongoDB – you can see the update matched count is now one, so it will now be updated with the latest information. If you verified the second highlighted line you can see the price was updated to $31.99 (Line #11).

// Upsert Item Java Model into MongoDB (updateOne)
// ---Item #2---
final Item item2 = new Item();
item2.setId("1454163352");
item2.setItemId("B00DUHACEE");
item2.setDescription("SterlingPro French Coffee Press"
				+ " -- 8 Cup/4 Mug (1 liter, 34 oz), Chrome");
item2.setManufacturer("SterlingPro");
item2.setDepartment("kitchen");
item2.setCategory("Coffee Machines");
item2.setSubCategory("French Press");
item2.setListPrice(68.00);
item2.setPrice(29.97);
item2.setQuantity(8);

status = updateCollection(collection, item2);
System.out.println("Status of Update: " + status);
showDocumentByID(collection, item2.getId());

item2.setPrice(31.99);
status = updateCollection(collection, item2);
System.out.println("Status of Update: " + status);
showDocumentByID(collection, item2.getId());

Seeing the Results of the UpdateOne for Upsert Operation Test

Item #1454163352: {"_id":"1454163352","item-id":"B00DUHACEE","description":"SterlingPro French Coffee Press -- 8 Cup/4 Mug (1 liter, 34 oz), Chrome","manufacturer":"SterlingPro","department":"kitchen","category":"Coffee Machines","sub-category":"French Press","price":29.97,"list-price":68.0,"quantity":8}
Update Matched Count....: 0
Update Modified Count...: 0
Status of Update: true
{ "_id" : "1454163352", "item-id" : "B00DUHACEE", "description" : "SterlingPro French Coffee Press -- 8 Cup/4 Mug (1 liter, 34 oz), Chrome", "manufacturer" : "SterlingPro", "department" : "kitchen", "category" : "Coffee Machines", "sub-category" : "French Press", "price" : 29.97, "list-price" : 68.0, "quantity" : 8 }

Item #1454163352: {"_id":"1454163352","item-id":"B00DUHACEE","description":"SterlingPro French Coffee Press -- 8 Cup/4 Mug (1 liter, 34 oz), Chrome","manufacturer":"SterlingPro","department":"kitchen","category":"Coffee Machines","sub-category":"French Press","price":31.99,"list-price":68.0,"quantity":8}
Update Matched Count....: 1
Update Modified Count...: 1
Status of Update: true
{ "_id" : "1454163352", "item-id" : "B00DUHACEE", "description" : "SterlingPro French Coffee Press -- 8 Cup/4 Mug (1 liter, 34 oz), Chrome", "manufacturer" : "SterlingPro", "department" : "kitchen", "category" : "Coffee Machines", "sub-category" : "French Press", "price" : 31.99, "list-price" : 68.0, "quantity" : 8 }
mongodb_crud_final

Using MongoDB 3.2 replaceOne Upsert Java Examples

ReplaceOne works by replacing the entire document with the current one being passed into the method with the exception of the _id field. What it means is that the document can have an entire different set of fields associated with it, or in the case of our example, we will only have the fields we set populated and all other fields will be left unset (set to their default values of empty or zero).

IMPORTANT
After the replace operation, the document will contain ONLY the fields that we set, the other fields will remain unset.
public static boolean replaceUpsertCollection(
		final MongoCollection<Document> collection, final Item item) {
	boolean status = true;
	ObjectMapper mapper = new ObjectMapper();
	String jsonString;

	try {
		jsonString = mapper.writeValueAsString(item);
		// Insert JSON into MongoDB
		System.out.println(String.format("Item #%s: %s", item.getId(),
				jsonString));
		BasicDBObject query = new BasicDBObject();
		query.append("_id", item.getId());
		Document doc = Document.parse(jsonString);
		UpdateResult result = collection.replaceOne(query, doc,
				(new UpdateOptions()).upsert(true));
		System.out.println("Replace Matched Count....: "
				+ result.getMatchedCount());
		System.out.println("Replace Modified Count...: "
				+ result.getModifiedCount());
	} catch (MongoWriteException mwe) {
		status = false;
	} catch (IOException e) {
		status = false;
	}

	return status;
}

Testing the replaceOne for Upsert Operation

When the replaceOne is executed for the first time our MongoDB collection contained the document with _id=1454163352 and all of the fields were set and fully populated (Line #1). We created a new object (item3) and only set the Description, Category and SubCategory fields. All of the other fields in the object will be either null or zero (0). After we call replaceUpsertCollection(collection, item3) you can see that document has been replaced with our new document in MongoDB(Line #6). The second call to replaceOne is done after we have added the price of $31.99 to the instance of item3. Now you can see that the document has been updated to reflect the new price of $31.99.

// Upsert Item Java Model into MongoDB (replacOne)
// ---Item #3---
final Item item3 = new Item();
item3.setId("1454163352");
item3.setDescription("SterlingPro French Coffee Press");
item3.setCategory("Coffee Machines");
item3.setSubCategory("French Press");

status = replaceUpsertCollection(collection, item3);
System.out.println("Status of Update: " + status);
showDocumentByID(collection, item3.getId());

item3.setPrice(31.99);
status = replaceUpsertCollection(collection, item3);
System.out.println("Status of Update: " + status);
showDocumentByID(collection, item3.getId());

Seeing the Results of the ReplaceOne for Upsert Operation Test

{ "_id" : "1454163352", "item-id" : "B00DUHACEE", "description" : "SterlingPro French Coffee Press -- 8 Cup/4 Mug (1 liter, 34 oz), Chrome", "manufacturer" : "SterlingPro", "department" : "kitchen", "category" : "Coffee Machines", "sub-category" : "French Press", "price" : 29.97, "list-price" : 68.0, "quantity" : 8 }
Item #1454163352: {"_id":"1454163352","item-id":null,"description":"SterlingPro French Coffee Press","manufacturer":null,"department":null,"category":"Coffee Machines","sub-category":"French Press","price":0.0,"list-price":0.0,"quantity":0}
Replace Matched Count....: 1
Replace Modified Count...: 1
Status of Update: true
{ "_id" : "1454163352", "item-id" : null, "description" : "SterlingPro French Coffee Press", "manufacturer" : null, "department" : null, "category" : "Coffee Machines", "sub-category" : "French Press", "price" : 0.0, "list-price" : 0.0, "quantity" : 0 }
Item #1454163352: {"_id":"1454163352","item-id":null,"description":"SterlingPro French Coffee Press","manufacturer":null,"department":null,"category":"Coffee Machines","sub-category":"French Press","price":31.99,"list-price":0.0,"quantity":0}
Replace Matched Count....: 1
Replace Modified Count...: 1
Status of Update: true
{ "_id" : "1454163352", "item-id" : null, "description" : "SterlingPro French Coffee Press", "manufacturer" : null, "department" : null, "category" : "Coffee Machines", "sub-category" : "French Press", "price" : 31.99, "list-price" : 0.0, "quantity" : 0 }
mongodb_crud_after_replace

Using MongoDB 3.2 findOneAndUpdate Java Example

findOneAndUpdate works by performing the querying and update as one atomic operation in MongoDB. Depending on the FindOneAndUpdateOptions() that are set. In my example, I have turned on the upsert flag to true. The findOneAndUpdate operation will update the first matching document in the collection that matches the query filter.

IMPORTANT
findOneAndUpdate has the option to return either the original document or the newly modified document.
public static Document findAndUpdateCollection(
	final MongoCollection<Document> collection, final Item item) {
	ObjectMapper mapper = new ObjectMapper();
	Document resultDocument = null;
	String jsonString;

	try {
		// findOneAndUpdate using JSON into MongoDB
		jsonString = mapper.writeValueAsString(item);
		System.out.println(String.format("Item #%s: %s", item.getId(),
			jsonString));
		BasicDBObject query = new BasicDBObject();
		query.append("_id", item.getId());
		BasicDBObject doc = BasicDBObject.parse(jsonString);
		Bson newDocument = new Document("$set", doc);
		resultDocument = collection.findOneAndUpdate(query,
			newDocument, (new FindOneAndUpdateOptions()).upsert(true));
	} catch (IOException e) {
		e.printStackTrace();
	}

	return resultDocument;
}

Testing the findOneAndUpdate Operation

item3.setQuantity(12);
Document updatedDoc = findAndUpdateCollection(collection, item3);
System.out.println("Updated Document: " + updatedDoc);
showDocumentByID(collection, item3.getId());

Seeing the Results of the findOneAndUpdate Operation Test

For this test we call the method findAndUpdateCollection(collection, item3) after having set the quantity in item3 instance to 12. You will notice that upon completion the original document is returned to us which is displayed after the text ‘Updated Document:’ (Line #2). However, you will note that the document that is stored in the MongoDB collection has been properly updated (Line #3).

Item #1454163352: {"_id":"1454163352","item-id":null,"description":"SterlingPro French Coffee Press","manufacturer":null,"department":null,"category":"Coffee Machines","sub-category":"French Press","price":31.99,"list-price":72.99,"quantity":12}
Updated Document: Document{{_id=1454163352, item-id=null, description=SterlingPro French Coffee Press, manufacturer=null, department=null, category=Coffee Machines, sub-category=French Press, price=31.99, list-price=72.99, quantity=0}}
{ "_id" : "1454163352", "item-id" : null, "description" : "SterlingPro French Coffee Press", "manufacturer" : null, "department" : null, "category" : "Coffee Machines", "sub-category" : "French Press", "price" : 31.99, "list-price" : 72.99, "quantity" : 12 }

The Complete Program (MongoDBCrudExample.java)

package com.avaldes.tutorial;

import java.io.IOException;

import org.bson.Document;
import org.bson.conversions.Bson;
import org.codehaus.jackson.map.ObjectMapper;

import com.avaldes.model.Item;
import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.MongoClient;
import com.mongodb.MongoWriteException;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.FindOneAndUpdateOptions;
import com.mongodb.client.model.UpdateOptions;
import com.mongodb.client.result.DeleteResult;
import com.mongodb.client.result.UpdateResult;

public class MongoDBCrudExample {

  public static void main(String[] args) {
    mongoTestCRUDOperations();
  }

  public static void mongoTestCRUDOperations() {
    MongoClient mongoClient = null;

    try {
      System.out
          .println("Using mongoTestCRUDOperations() to 'test' database...");
      mongoClient = new MongoClient();
      MongoDatabase db = mongoClient.getDatabase("test");

      MongoCollection<Document> collection = db
          .getCollection("inventory");

      // Show all documents in the collection
      showAllDocuments(collection);

      // Insert Item Java Model into MongoDB
      // ---Item #1---
      final Item item1 = new Item();
      item1.setId("1454163351");
      item1.setItemId("B0037ZG3DS");
      item1
          .setDescription("Mr. Coffee BVMC-PSTX91 Optimal Brew 10-Cup "
              + "Thermal Coffeemaker, Black/Stainless Steel");
      item1.setManufacturer("Mr. Coffee");
      item1.setDepartment("kitchen");
      item1.setCategory("Coffee Machines");
      item1.setSubCategory("Thermal Carafe");
      item1.setListPrice(89.99);
      item1.setPrice(69.00);
      item1.setQuantity(3);

      boolean status = insertIntoCollection(collection, item1);
      System.out.println("Status of Insert: " + status);

      // Upsert Item Java Model into MongoDB (updateOne)
      // ---Item #2---
      final Item item2 = new Item();
      item2.setId("1454163352");
      item2.setItemId("B00DUHACEE");
      item2
          .setDescription("SterlingPro French Coffee Press -- 8 Cup/4 Mug "
              + "(1 liter, 34 oz), Chrome");
      item2.setManufacturer("SterlingPro");
      item2.setDepartment("kitchen");
      item2.setCategory("Coffee Machines");
      item2.setSubCategory("French Press");
      item2.setListPrice(68.00);
      item2.setPrice(29.97);
      item2.setQuantity(8);

      status = updateCollection(collection, item2);
      System.out.println("Status of Update: " + status);
      showDocumentByID(collection, item2.getId());

      item2.setPrice(31.99);
      status = updateCollection(collection, item2);
      System.out.println("Status of Update: " + status);
      showDocumentByID(collection, item2.getId());

      // Upsert Item Java Model into MongoDB (replacOne)
      // ---Item #3---
      final Item item3 = new Item();
      item3.setId("1454163352");
      item3.setDescription("SterlingPro French Coffee Press");
      item3.setCategory("Coffee Machines");
      item3.setSubCategory("French Press");

      status = replaceUpsertCollection(collection, item3);
      System.out.println("Status of Update: " + status);
      showDocumentByID(collection, item3.getId());

      item3.setPrice(31.99);
      status = replaceUpsertCollection(collection, item3);
      System.out.println("Status of Update: " + status);
      showDocumentByID(collection, item3.getId());

      item3.setListPrice(72.99);
      status = updateCollection(collection, item3);
      System.out.println("Status of Update: " + status);
      showDocumentByID(collection, item3.getId());

      item3.setQuantity(12);
      Document updatedDoc = findAndUpdateCollection(collection, item3);
      System.out.println("Updated Document: " + updatedDoc);
      showDocumentByID(collection, item3.getId());

      // Show all documents in the collection before deletes
      System.out.println("-----[ BEFORE DELETES ]-----");
      showAllDocuments(collection);

      // Find the ID using findOneAndDelete
      Document deletedDoc = findOneAndDeleteCollection(collection,
          "1454163350");
      System.out.println("Deleted Document: " + deletedDoc);

      // Find the ID using deleteOne
      DeleteResult deletedResult = deleteOneFromCollection(
          collection, "1454163349");
      System.out.println("Deleted Document: " + deletedResult);

      // Show all documents in the collection after deletes
      System.out.println("-----[ AFTER DELETES ]-----");
      showAllDocuments(collection);
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      mongoClient.close();
    }
  }

  public static boolean insertIntoCollection(
      final MongoCollection<Document> collection, final Item item) {
    // Use Jackson to convert Object to JSON String
    ObjectMapper mapper = new ObjectMapper();
    String jsonString;
    boolean status = true;

    try {
      jsonString = mapper.writeValueAsString(item);
      // Insert JSON into MongoDB
      System.out.println(String.format("Item #%s: %s", item.getId(),
          jsonString));
      Document doc = Document.parse(jsonString);
      collection.insertOne(doc);
    } catch (MongoWriteException mwe) {
      status = false;
    } catch (IOException e) {
      status = false;
    }
    return status;
  }

  public static boolean replaceUpsertCollection(
      final MongoCollection<Document> collection, final Item item) {
    boolean status = true;
    ObjectMapper mapper = new ObjectMapper();
    String jsonString;

    try {
      jsonString = mapper.writeValueAsString(item);
      // Insert JSON into MongoDB
      System.out.println(String.format("Item #%s: %s", item.getId(),
          jsonString));
      BasicDBObject query = new BasicDBObject();
      query.append("_id", item.getId());
      Document doc = Document.parse(jsonString);
      UpdateResult result = collection.replaceOne(query, doc,
          (new UpdateOptions()).upsert(true));
      System.out.println("Replace Matched Count....: "
          + result.getMatchedCount());
      System.out.println("Replace Modified Count...: "
          + result.getModifiedCount());
    } catch (MongoWriteException mwe) {
      status = false;
    } catch (IOException e) {
      status = false;
    }

    return status;
  }

  public static boolean updateCollection(
      final MongoCollection<Document> collection, final Item item) {
    boolean status = true;
    ObjectMapper mapper = new ObjectMapper();
    String jsonString;

    try {
      jsonString = mapper.writeValueAsString(item);
      // update/upsert using JSON into MongoDB
      System.out.println(String.format("Item #%s: %s", item.getId(),
          jsonString));
      BasicDBObject query = new BasicDBObject();
      query.append("_id", item.getId());
      BasicDBObject doc = BasicDBObject.parse(jsonString);
      Bson newDocument = new Document("$set", doc);
      UpdateResult result = collection.updateOne(query, newDocument,
          (new UpdateOptions()).upsert(true));
      System.out.println("Update Matched Count....: "
          + result.getMatchedCount());
      System.out.println("Update Modified Count...: "
          + result.getModifiedCount());
    } catch (MongoWriteException mwe) {
      status = false;
    } catch (IOException e) {
      status = false;
    }

    return status;
  }

  public static Document findAndUpdateCollection(
      final MongoCollection<Document> collection, final Item item) {
    ObjectMapper mapper = new ObjectMapper();
    Document resultDocument = null;
    String jsonString;

    try {
      // findOneAndUpdate using JSON into MongoDB
      jsonString = mapper.writeValueAsString(item);
      System.out.println(String.format("Item #%s: %s", item.getId(),
          jsonString));
      BasicDBObject query = new BasicDBObject();
      query.append("_id", item.getId());
      BasicDBObject doc = BasicDBObject.parse(jsonString);
      Bson newDocument = new Document("$set", doc);
      resultDocument = collection.findOneAndUpdate(query,
          newDocument, (new FindOneAndUpdateOptions()).upsert(true));
    } catch (IOException e) {
      e.printStackTrace();
    }

    return resultDocument;
  }

  public static Document findOneAndDeleteCollection(
      final MongoCollection<Document> collection, final String id) {
    Document resultDocument = null;

    // findOneAndDelete from MongoDB
    System.out.println(
      "Using findOneAndDeleteCollection to delete ID: " + id);
    BasicDBObject query = new BasicDBObject();
    query.append("_id", id);
    resultDocument = collection.findOneAndDelete(query);

    return resultDocument;
  }

  public static DeleteResult deleteOneFromCollection(
      final MongoCollection<Document> collection, final String id) {
    DeleteResult resultDocument = null;

    // findOneAndDelete from MongoDB
    System.out.println(
        "Using deleteOneFromCollection to delete ID: " + id);
    BasicDBObject query = new BasicDBObject();
    query.append("_id", id);
    resultDocument = collection.deleteOne(query);

    return resultDocument;
  }

  public static void showDocumentByID(
      final MongoCollection<Document> collection, final String id) {
    BasicDBObject query = new BasicDBObject();
    query.append("_id", id);

    for (Document doc : collection.find(query)) {
      System.out.println(doc.toJson());
    }
  }

  public static void showAllDocuments(
      final MongoCollection<Document> collection) {
    System.out
        .println("----[All Items in the Inventory Collection]----");
    for (Document doc : collection.find()) {
      System.out.println(doc.toJson());
    }
  }

  public static void showAllDocs(final DBCollection collection) {
    DBCursor cursor = (DBCursor) collection.find().iterator();
    try {
      while (cursor.hasNext()) {
        System.out.println(cursor.next().toString());
      }
    } finally {
      cursor.close();
    }
  }
}

The Model (Item.java)

package com.avaldes.model;

import org.codehaus.jackson.annotate.JsonProperty;
import org.codehaus.jackson.annotate.JsonPropertyOrder;

@JsonPropertyOrder({"_id", "item-id", "description", 
                    "manufacturer", "dept", "category", 
                    "sub-category", "price", "list-price", "quantity"}) 
public class Item {
  private String id;
  private String itemId;
  private String description;
  private String manufacturer;
  private String department;
  private String category;
  private String subCategory;
  private double price;
  private double listPrice;
  private int quantity;

  @JsonProperty("_id")
  public String getId() {
    return id;
  }

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

  @JsonProperty("item-id")
  public String getItemId() {
    return itemId;
  }

  public void setItemId(String itemId) {
    this.itemId = itemId;
  }

  @JsonProperty("description")
  public String getDescription() {
    return description;
  }

  public void setDescription(String description) {
    this.description = description;
  }

  @JsonProperty("manufacturer")
  public String getManufacturer() {
    return manufacturer;
  }

  public void setManufacturer(String manufacturer) {
    this.manufacturer = manufacturer;
  }

  @JsonProperty("dept")
  public String getDepartment() {
    return department;
  }

  public void setDepartment(String department) {
    this.department = department;
  }

  @JsonProperty("category")
  public String getCategory() {
    return category;
  }

  public void setCategory(String category) {
    this.category = category;
  }

  @JsonProperty("sub-category")
  public String getSubCategory() {
    return subCategory;
  }

  public void setSubCategory(String subCategory) {
    this.subCategory = subCategory;
  }

  @JsonProperty("price")
  public double getPrice() {
    return price;
  }

  public void setPrice(double price) {
    this.price = price;
  }

  @JsonProperty("list-price")
  public double getListPrice() {
    return listPrice;
  }

  public void setListPrice(double listPrice) {
    this.listPrice = listPrice;
  }

  @JsonProperty("quantity")
  public int getQuantity() {
    return quantity;
  }

  public void setQuantity(int quantity) {
    this.quantity = quantity;
  }

  @Override
  public String toString() {
    return "Item [id=" + id + ", itemId=" + itemId + ", description="
        + description + ", manufacturer=" + manufacturer + ", department="
        + department + ", category=" + category + ", subCategory="
        + subCategory + ", price=" + price + ", listPrice=" + listPrice
        + ", quantity=" + quantity + "]";
  }
}

JSON Sample Documents

I have included these JSON Documents as reference and to allow you to easily create the Mongo collection locally.

{
    "_id" : "1454163779",
    "item-id" : "B0047Y0UQO",
    "description" : "Mr. Coffee BVMC-SJX33GT 12-Cup Programmable Coffeemaker, Chrome",
    "manufacturer" : "Mr. Coffee",
    "dept" : "kitchen",
    "category" : "Coffee Machines",
    "sub-category" : "Programmable Coffee Makers",
    "price" : 29.7399999999999980,
    "list-price" : 39.9900000000000020,
    "quantity" : 13
}
{
    "_id" : "1454164107",
    "item-id" : "B0008JIW8U",
    "description" : "Mr. Coffee DRX5 4-Cup Programmable Coffeemaker, Black",
    "manufacturer" : "Mr. Coffee",
    "dept" : "kitchen",
    "category" : "Coffee Machines",
    "sub-category" : "Programmable Coffee Makers",
    "price" : 24.9899999999999980,
    "list-price" : 19.9899999999999980,
    "quantity" : 32
}
{
    "_id" : "1454163343",
    "item-id" : "B001NXC5YC",
    "description" : "Black & Decker DCM600B 5-Cup Coffeemaker, Black",
    "manufacturer" : "Black & Decker",
    "dept" : "kitchen",
    "category" : "Coffee Machines",
    "sub-category" : "Programmable Coffee Makers",
    "price" : 19.9899999999999980,
    "list-price" : 14.9600000000000010,
    "quantity" : 65
}
{
    "_id" : "1454163344",
    "item-id" : "B003KYSLMC",
    "description" : "Cuisinart CHW-12 Coffee Plus 12-Cup Programmable Coffeemaker with Hot Water System, Black/Stainless",
    "manufacturer" : "Cuisinart",
    "dept" : "kitchen",
    "category" : "Coffee Machines",
    "sub-category" : "Programmable Coffee Makers",
    "price" : 185.0000000000000000,
    "list-price" : 91.8900000000000010,
    "quantity" : 18
}
{
    "_id" : "1454163345",
    "item-id" : "B003TOAM98",
    "description" : "DeLonghi DCF2212T 12-Cup Glass Carafe Drip Coffee Maker, Black",
    "manufacturer" : "DeLonghi",
    "dept" : "kitchen",
    "category" : "Coffee Machines",
    "sub-category" : "Programmable Coffee Makers",
    "price" : 70.0000000000000000,
    "list-price" : 53.9900000000000020,
    "quantity" : 21
}
{
    "_id" : "1454163346",
    "item-id" : "B001A61BMO",
    "description" : "Kalorik 1000-Watt 12-Cup Programmable Coffeemaker, Copper",
    "manufacturer" : "Kalorik",
    "dept" : "kitchen",
    "category" : "Coffee Machines",
    "sub-category" : "Programmable Coffee Makers",
    "price" : 99.9899999999999950,
    "list-price" : 36.9500000000000030,
    "quantity" : 26
}
{
    "_id" : "1454163348",
    "item-id" : "B000T9SCZ2",
    "description" : "Cuisinart DGB-700BC Grind-and-Brew 12-Cup Automatic Coffeemaker, Brushed Chrome/Black",
    "manufacturer" : "Cuisinart",
    "dept" : "kitchen",
    "category" : "Coffee Machines",
    "sub-category" : "Built-in Griders",
    "price" : 305.0000000000000000,
    "list-price" : 159.9900000000000100,
    "quantity" : 6
}
{
    "_id" : "1454163349",
    "item-id" : "B002EVOVPI",
    "description" : "Capresso 464.05 CoffeeTeam GS 10-Cup Digital Coffeemaker with Conical Burr Grinder",
    "manufacturer" : "Capresso",
    "dept" : "kitchen",
    "category" : "Coffee Machines",
    "sub-category" : "Built-in Griders",
    "price" : 250.0000000000000000,
    "list-price" : 164.9900000000000100,
    "quantity" : 4
}
{
    "_id" : "1454163350",
    "item-id" : "B002IASYA8",
    "description" : "Cuisinart Fully Automatic Burr Grind & Brew Thermal 12 Cup Coffeemaker DGB900BCC",
    "manufacturer" : "Cuisinart",
    "dept" : "kitchen",
    "category" : "Coffee Machines",
    "sub-category" : "Built-in Griders",
    "price" : 249.9900000000000100,
    "list-price" : 189.9900000000000100,
    "quantity" : 6
}

Testing out our MongoDBCrudExample Application

Using mongoTestCRUDOperations() to 'test' database...
----[All Items in the Inventory Collection]----
{ "_id" : "1454163779", "item-id" : "B0047Y0UQO", "description" : "Mr. Coffee BVMC-SJX33GT 12-Cup Programmable Coffeemaker, Chrome", "manufacturer" : "Mr. Coffee", "dept" : "kitchen", "category" : "Coffee Machines", "sub-category" : "Programmable Coffee Makers", "price" : 29.74, "list-price" : 39.99, "quantity" : 13 }
{ "_id" : "1454164107", "item-id" : "B0008JIW8U", "description" : "Mr. Coffee DRX5 4-Cup Programmable Coffeemaker, Black", "manufacturer" : "Mr. Coffee", "dept" : "kitchen", "category" : "Coffee Machines", "sub-category" : "Programmable Coffee Makers", "price" : 24.99, "list-price" : 19.99, "quantity" : 32 }
{ "_id" : "1454163343", "item-id" : "B001NXC5YC", "description" : "Black & Decker DCM600B 5-Cup Coffeemaker, Black", "manufacturer" : "Black & Decker", "dept" : "kitchen", "category" : "Coffee Machines", "sub-category" : "Programmable Coffee Makers", "price" : 19.99, "list-price" : 14.96, "quantity" : 65 }
{ "_id" : "1454163344", "item-id" : "B003KYSLMC", "description" : "Cuisinart CHW-12 Coffee Plus 12-Cup Programmable Coffeemaker with Hot Water System, Black/Stainless", "manufacturer" : "Cuisinart", "dept" : "kitchen", "category" : "Coffee Machines", "sub-category" : "Programmable Coffee Makers", "price" : 185.0, "list-price" : 91.89, "quantity" : 18 }
{ "_id" : "1454163345", "item-id" : "B003TOAM98", "description" : "DeLonghi DCF2212T 12-Cup Glass Carafe Drip Coffee Maker, Black", "manufacturer" : "DeLonghi", "dept" : "kitchen", "category" : "Coffee Machines", "sub-category" : "Programmable Coffee Makers", "price" : 70.0, "list-price" : 53.99, "quantity" : 21 }
{ "_id" : "1454163346", "item-id" : "B001A61BMO", "description" : "Kalorik 1000-Watt 12-Cup Programmable Coffeemaker, Copper", "manufacturer" : "Kalorik", "dept" : "kitchen", "category" : "Coffee Machines", "sub-category" : "Programmable Coffee Makers", "price" : 99.99, "list-price" : 36.95, "quantity" : 26 }
{ "_id" : "1454163348", "item-id" : "B000T9SCZ2", "description" : "Cuisinart DGB-700BC Grind-and-Brew 12-Cup Automatic Coffeemaker, Brushed Chrome/Black", "manufacturer" : "Cuisinart", "dept" : "kitchen", "category" : "Coffee Machines", "sub-category" : "Built-in Griders", "price" : 305.0, "list-price" : 159.99, "quantity" : 6 }
{ "_id" : "1454163349", "item-id" : "B002EVOVPI", "description" : "Capresso 464.05 CoffeeTeam GS 10-Cup Digital Coffeemaker with Conical Burr Grinder", "manufacturer" : "Capresso", "dept" : "kitchen", "category" : "Coffee Machines", "sub-category" : "Built-in Griders", "price" : 250.0, "list-price" : 164.99, "quantity" : 4 }
{ "_id" : "1454163350", "item-id" : "B002IASYA8", "description" : "Cuisinart Fully Automatic Burr Grind & Brew Thermal 12 Cup Coffeemaker DGB900BCC", "manufacturer" : "Cuisinart", "dept" : "kitchen", "category" : "Coffee Machines", "sub-category" : "Built-in Griders", "price" : 249.99, "list-price" : 189.99, "quantity" : 6 }
Item #1454163351: {"_id":"1454163351","item-id":"B0037ZG3DS","description":"Mr. Coffee BVMC-PSTX91 Optimal Brew 10-Cup Thermal Coffeemaker, Black/Stainless Steel","manufacturer":"Mr. Coffee","dept":"kitchen","category":"Coffee Machines","sub-category":"Thermal Carafe","price":69.0,"list-price":89.99,"quantity":3}
Status of Insert: true
Item #1454163352: {"_id":"1454163352","item-id":"B00DUHACEE","description":"SterlingPro French Coffee Press -- 8 Cup/4 Mug (1 liter, 34 oz), Chrome","manufacturer":"SterlingPro","dept":"kitchen","category":"Coffee Machines","sub-category":"French Press","price":29.97,"list-price":68.0,"quantity":8}
Update Matched Count....: 0
Update Modified Count...: 0
Status of Update: true
{ "_id" : "1454163352", "item-id" : "B00DUHACEE", "description" : "SterlingPro French Coffee Press -- 8 Cup/4 Mug (1 liter, 34 oz), Chrome", "manufacturer" : "SterlingPro", "dept" : "kitchen", "category" : "Coffee Machines", "sub-category" : "French Press", "price" : 29.97, "list-price" : 68.0, "quantity" : 8 }
Item #1454163352: {"_id":"1454163352","item-id":"B00DUHACEE","description":"SterlingPro French Coffee Press -- 8 Cup/4 Mug (1 liter, 34 oz), Chrome","manufacturer":"SterlingPro","dept":"kitchen","category":"Coffee Machines","sub-category":"French Press","price":31.99,"list-price":68.0,"quantity":8}
Update Matched Count....: 1
Update Modified Count...: 1
Status of Update: true
{ "_id" : "1454163352", "item-id" : "B00DUHACEE", "description" : "SterlingPro French Coffee Press -- 8 Cup/4 Mug (1 liter, 34 oz), Chrome", "manufacturer" : "SterlingPro", "dept" : "kitchen", "category" : "Coffee Machines", "sub-category" : "French Press", "price" : 31.99, "list-price" : 68.0, "quantity" : 8 }
Item #1454163352: {"_id":"1454163352","item-id":null,"description":"SterlingPro French Coffee Press","manufacturer":null,"dept":null,"category":"Coffee Machines","sub-category":"French Press","price":0.0,"list-price":0.0,"quantity":0}
Replace Matched Count....: 1
Replace Modified Count...: 1
Status of Update: true
{ "_id" : "1454163352", "item-id" : null, "description" : "SterlingPro French Coffee Press", "manufacturer" : null, "dept" : null, "category" : "Coffee Machines", "sub-category" : "French Press", "price" : 0.0, "list-price" : 0.0, "quantity" : 0 }
Item #1454163352: {"_id":"1454163352","item-id":null,"description":"SterlingPro French Coffee Press","manufacturer":null,"dept":null,"category":"Coffee Machines","sub-category":"French Press","price":31.99,"list-price":0.0,"quantity":0}
Replace Matched Count....: 1
Replace Modified Count...: 1
Status of Update: true
{ "_id" : "1454163352", "item-id" : null, "description" : "SterlingPro French Coffee Press", "manufacturer" : null, "dept" : null, "category" : "Coffee Machines", "sub-category" : "French Press", "price" : 31.99, "list-price" : 0.0, "quantity" : 0 }
Item #1454163352: {"_id":"1454163352","item-id":null,"description":"SterlingPro French Coffee Press","manufacturer":null,"dept":null,"category":"Coffee Machines","sub-category":"French Press","price":31.99,"list-price":72.99,"quantity":0}
Update Matched Count....: 1
Update Modified Count...: 1
Status of Update: true
{ "_id" : "1454163352", "item-id" : null, "description" : "SterlingPro French Coffee Press", "manufacturer" : null, "dept" : null, "category" : "Coffee Machines", "sub-category" : "French Press", "price" : 31.99, "list-price" : 72.99, "quantity" : 0 }
Item #1454163352: {"_id":"1454163352","item-id":null,"description":"SterlingPro French Coffee Press","manufacturer":null,"dept":null,"category":"Coffee Machines","sub-category":"French Press","price":31.99,"list-price":72.99,"quantity":12}
Updated Document: Document{{_id=1454163352, item-id=null, description=SterlingPro French Coffee Press, manufacturer=null, dept=null, category=Coffee Machines, sub-category=French Press, price=31.99, list-price=72.99, quantity=0}}
{ "_id" : "1454163352", "item-id" : null, "description" : "SterlingPro French Coffee Press", "manufacturer" : null, "dept" : null, "category" : "Coffee Machines", "sub-category" : "French Press", "price" : 31.99, "list-price" : 72.99, "quantity" : 12 }
-----[ BEFORE DELETES ]-----
----[All Items in the Inventory Collection]----
{ "_id" : "1454163779", "item-id" : "B0047Y0UQO", "description" : "Mr. Coffee BVMC-SJX33GT 12-Cup Programmable Coffeemaker, Chrome", "manufacturer" : "Mr. Coffee", "dept" : "kitchen", "category" : "Coffee Machines", "sub-category" : "Programmable Coffee Makers", "price" : 29.74, "list-price" : 39.99, "quantity" : 13 }
{ "_id" : "1454164107", "item-id" : "B0008JIW8U", "description" : "Mr. Coffee DRX5 4-Cup Programmable Coffeemaker, Black", "manufacturer" : "Mr. Coffee", "dept" : "kitchen", "category" : "Coffee Machines", "sub-category" : "Programmable Coffee Makers", "price" : 24.99, "list-price" : 19.99, "quantity" : 32 }
{ "_id" : "1454163343", "item-id" : "B001NXC5YC", "description" : "Black & Decker DCM600B 5-Cup Coffeemaker, Black", "manufacturer" : "Black & Decker", "dept" : "kitchen", "category" : "Coffee Machines", "sub-category" : "Programmable Coffee Makers", "price" : 19.99, "list-price" : 14.96, "quantity" : 65 }
{ "_id" : "1454163344", "item-id" : "B003KYSLMC", "description" : "Cuisinart CHW-12 Coffee Plus 12-Cup Programmable Coffeemaker with Hot Water System, Black/Stainless", "manufacturer" : "Cuisinart", "dept" : "kitchen", "category" : "Coffee Machines", "sub-category" : "Programmable Coffee Makers", "price" : 185.0, "list-price" : 91.89, "quantity" : 18 }
{ "_id" : "1454163345", "item-id" : "B003TOAM98", "description" : "DeLonghi DCF2212T 12-Cup Glass Carafe Drip Coffee Maker, Black", "manufacturer" : "DeLonghi", "dept" : "kitchen", "category" : "Coffee Machines", "sub-category" : "Programmable Coffee Makers", "price" : 70.0, "list-price" : 53.99, "quantity" : 21 }
{ "_id" : "1454163346", "item-id" : "B001A61BMO", "description" : "Kalorik 1000-Watt 12-Cup Programmable Coffeemaker, Copper", "manufacturer" : "Kalorik", "dept" : "kitchen", "category" : "Coffee Machines", "sub-category" : "Programmable Coffee Makers", "price" : 99.99, "list-price" : 36.95, "quantity" : 26 }
{ "_id" : "1454163348", "item-id" : "B000T9SCZ2", "description" : "Cuisinart DGB-700BC Grind-and-Brew 12-Cup Automatic Coffeemaker, Brushed Chrome/Black", "manufacturer" : "Cuisinart", "dept" : "kitchen", "category" : "Coffee Machines", "sub-category" : "Built-in Griders", "price" : 305.0, "list-price" : 159.99, "quantity" : 6 }
{ "_id" : "1454163349", "item-id" : "B002EVOVPI", "description" : "Capresso 464.05 CoffeeTeam GS 10-Cup Digital Coffeemaker with Conical Burr Grinder", "manufacturer" : "Capresso", "dept" : "kitchen", "category" : "Coffee Machines", "sub-category" : "Built-in Griders", "price" : 250.0, "list-price" : 164.99, "quantity" : 4 }
{ "_id" : "1454163350", "item-id" : "B002IASYA8", "description" : "Cuisinart Fully Automatic Burr Grind & Brew Thermal 12 Cup Coffeemaker DGB900BCC", "manufacturer" : "Cuisinart", "dept" : "kitchen", "category" : "Coffee Machines", "sub-category" : "Built-in Griders", "price" : 249.99, "list-price" : 189.99, "quantity" : 6 }
{ "_id" : "1454163351", "item-id" : "B0037ZG3DS", "description" : "Mr. Coffee BVMC-PSTX91 Optimal Brew 10-Cup Thermal Coffeemaker, Black/Stainless Steel", "manufacturer" : "Mr. Coffee", "dept" : "kitchen", "category" : "Coffee Machines", "sub-category" : "Thermal Carafe", "price" : 69.0, "list-price" : 89.99, "quantity" : 3 }
{ "_id" : "1454163352", "item-id" : null, "description" : "SterlingPro French Coffee Press", "manufacturer" : null, "dept" : null, "category" : "Coffee Machines", "sub-category" : "French Press", "price" : 31.99, "list-price" : 72.99, "quantity" : 12 }
Using findOneAndDeleteCollection to delete ID: 1454163350
Deleted Document: Document{{_id=1454163350, item-id=B002IASYA8, description=Cuisinart Fully Automatic Burr Grind & Brew Thermal 12 Cup Coffeemaker DGB900BCC, manufacturer=Cuisinart, dept=kitchen, category=Coffee Machines, sub-category=Built-in Griders, price=249.99, list-price=189.99, quantity=6}}
Using deleteOneFromCollection to delete ID: 1454163349
Deleted Document: AcknowledgedDeleteResult{deletedCount=1}
-----[ AFTER DELETES ]-----
----[All Items in the Inventory Collection]----
{ "_id" : "1454163779", "item-id" : "B0047Y0UQO", "description" : "Mr. Coffee BVMC-SJX33GT 12-Cup Programmable Coffeemaker, Chrome", "manufacturer" : "Mr. Coffee", "dept" : "kitchen", "category" : "Coffee Machines", "sub-category" : "Programmable Coffee Makers", "price" : 29.74, "list-price" : 39.99, "quantity" : 13 }
{ "_id" : "1454164107", "item-id" : "B0008JIW8U", "description" : "Mr. Coffee DRX5 4-Cup Programmable Coffeemaker, Black", "manufacturer" : "Mr. Coffee", "dept" : "kitchen", "category" : "Coffee Machines", "sub-category" : "Programmable Coffee Makers", "price" : 24.99, "list-price" : 19.99, "quantity" : 32 }
{ "_id" : "1454163343", "item-id" : "B001NXC5YC", "description" : "Black & Decker DCM600B 5-Cup Coffeemaker, Black", "manufacturer" : "Black & Decker", "dept" : "kitchen", "category" : "Coffee Machines", "sub-category" : "Programmable Coffee Makers", "price" : 19.99, "list-price" : 14.96, "quantity" : 65 }
{ "_id" : "1454163344", "item-id" : "B003KYSLMC", "description" : "Cuisinart CHW-12 Coffee Plus 12-Cup Programmable Coffeemaker with Hot Water System, Black/Stainless", "manufacturer" : "Cuisinart", "dept" : "kitchen", "category" : "Coffee Machines", "sub-category" : "Programmable Coffee Makers", "price" : 185.0, "list-price" : 91.89, "quantity" : 18 }
{ "_id" : "1454163345", "item-id" : "B003TOAM98", "description" : "DeLonghi DCF2212T 12-Cup Glass Carafe Drip Coffee Maker, Black", "manufacturer" : "DeLonghi", "dept" : "kitchen", "category" : "Coffee Machines", "sub-category" : "Programmable Coffee Makers", "price" : 70.0, "list-price" : 53.99, "quantity" : 21 }
{ "_id" : "1454163346", "item-id" : "B001A61BMO", "description" : "Kalorik 1000-Watt 12-Cup Programmable Coffeemaker, Copper", "manufacturer" : "Kalorik", "dept" : "kitchen", "category" : "Coffee Machines", "sub-category" : "Programmable Coffee Makers", "price" : 99.99, "list-price" : 36.95, "quantity" : 26 }
{ "_id" : "1454163348", "item-id" : "B000T9SCZ2", "description" : "Cuisinart DGB-700BC Grind-and-Brew 12-Cup Automatic Coffeemaker, Brushed Chrome/Black", "manufacturer" : "Cuisinart", "dept" : "kitchen", "category" : "Coffee Machines", "sub-category" : "Built-in Griders", "price" : 305.0, "list-price" : 159.99, "quantity" : 6 }
{ "_id" : "1454163351", "item-id" : "B0037ZG3DS", "description" : "Mr. Coffee BVMC-PSTX91 Optimal Brew 10-Cup Thermal Coffeemaker, Black/Stainless Steel", "manufacturer" : "Mr. Coffee", "dept" : "kitchen", "category" : "Coffee Machines", "sub-category" : "Thermal Carafe", "price" : 69.0, "list-price" : 89.99, "quantity" : 3 }
{ "_id" : "1454163352", "item-id" : null, "description" : "SterlingPro French Coffee Press", "manufacturer" : null, "dept" : null, "category" : "Coffee Machines", "sub-category" : "French Press", "price" : 31.99, "list-price" : 72.99, "quantity" : 12 }

Download the Complete Source Code

That’s It!

I hope you enjoyed this tutorial. It was certainly a lot of fun putting it together and testing it out. Please continue to share the love and like us so that we can continue bringing you quality tutorials. Happy Coding!!!

java_crud_mongodb

Related Spring Posts

  • Creating Hello World Application using Spring MVC on Eclipse IDE
    In this tutorial we will go into some detail on how to set up your Eclipse IDE environment so that you can develop Spring MVC projects. In this post, we will create our first Spring MVC project with the all to familiar “Hello World” sample program.
  • Spring MVC Form Handling Example
    The following tutorial will guide you on writing a simple web based application which makes use of forms using Spring Web MVC framework. With this web application you will be able to interact with the customer entry form and enter all of the required values and submit them to the backend processes. I have taken the liberty of using CSS to beautify and transform the HTML page from a standard drab look and feel to a more appealing view.
  • Spring @RequestHeader Annotation Example
    In this tutorial, we will discuss the different ways that Spring MVC allow us to access HTTP headers using annotation. We will discuss how to access individual header fields from the request object as well accessing all the headers by supplying Map and then iterating through the LinkedHashMap collection. We will also show you how to set the headers in the response object.
  • Spring MVC Exception Handling using @ExceptionHandler with AngularJS GUI
    Good exception handling is a essential part of any well developed Application Framework and Spring MVC is no exception — pardon the pun. Spring MVC provides several different ways to handle exceptions in our applications. In this tutorial, we will cover Controller Based Exception Handling using the @ExceptionHandler annotation above the method that will handle it.
  • Spring RESTful Web Service Example with JSON and Jackson using Spring Tool Suite
    For this example, I will be using Spring Tool Suite (STS) as it is the best integrated development environment for building the Spring framework projects. Spring is today's leading framework for building Java, Enterprise Edition (Java EE) applications. One additional feature that makes Spring MVC so appealing is that it now also supports REST (REpresentational State Transfer) for build Web Services.
  • Spring MVC RESTful Web Service Example with Spring Data for MongoDB and ExtJS GUI
    This post will show another example of how to build a RESTful web service using Spring MVC 4.0.6, Spring Data for MongoDB 1.6.1 so that we can integrate the web application with a highly efficient datastore (MongoDB 2.6). In this tutorial we will walk you through building the web service and NoSQL database backend and show you how to implement CRUD (Create, Read, Update and Delete) operations.
  • Building DHTMLX Grid Panel User Interface with Spring MVC Rest and MongoDB Backend
    In this tutorial we will show how easy it is to use DHTMLX dhtmlxGrid component while loading JSON data with Ajax pulling in data from the Spring MVC REST web service from our MongoDB data source. You will see how simple it is to create a visually appealing experience for your client(s) with minimal javascript coding.
  • Spring MVC with JNDI Datasource for DB2 on AS/400 using Tomcat
    In this tutorial we will discuss how to set up Spring MVC web services and configure a JNDI Datasource using Tomcat and connect to IBM DB2 Database on a AS/400. JNDI (Java Naming and Directory Interface) provides and interface to multiple naming and directory services.
  • Java Spring MVC Email Example using Apache Velocity
    In this tutorial we will discuss how to set up a Java Spring MVC RESTful Webservice with Email using Apache Velocity to create a Velocity template that is used to create an HTML email message and embed an image, as shown below, using MIME Multipart Message.
  • Implementing Basic and Advanced Search using Angular Material Design, Grid-UI, Spring MVC REST API and MongoDB Example
    In this tutorial we will discuss how to implement basic and advanced search techniques in MongoDB using AngularJS and Google’s Material Design with Spring MVC REST API backend. The advanced search user interface (UI) will use logical operators and build a JSON object which contains the search field name, boolean or logical operator and the search value.
  • Spring MVC Interceptor using HandlerInterceptorAdapter Example
    In this tutorial we will discuss how to use the HandlerInterceptorAdapter abstract class to create a Spring MVC interceptor. These interceptors are used to apply some type of processing to the requests either before, after or after the complete request has finished executing.

Please Share Us on Social Media

Facebooktwittergoogle_plusredditpinterestlinkedinmail

Leave a Reply

Your email address will not be published. Required fields are marked *