dcsimg
September 25, 2016
Hot Topics:

NoSQL in Practice with a CRUD Application in Java

  • March 28, 2016
  • By Manoj Debnath
  • Send Email »
  • More Articles »

Creating a CRUD application in Java and MongoDB is pretty simple to begin with, although there are many intricacies involved as we dive deeper. The architectural foundation of the MongoDB JDBC library (version 3) quite aligns with the need of the Java developer. The API is intuitive and performs well with document schema that are translated in BSON. The JDBC driver version 3 has substantial changes in the API than its older (version 2) counterpart. So, the code written for one version can be significantly different than the other. Here, we mainly follow version 3 (the latest is v3.2.1 to be specific as of writing this article) APIs while creating a CRUD application in Java. The article gives you a glance at the practical aspects of NoSQL when implemented in MongoDB and Java.

A Glimpse into MongoDB

MongoDB is a document-oriented NoSQL database. If you are familiar with any relational databases, such as an RDBMS package, what a record is to relational database, a document is to MongoDB. Similarly, what a table is to relational database, a collection is to MongoDB. A data item in a document is structured as a key-value pairs much like a JSON object. The value can be of varied type. It may be a string, numbers, arrays, other document, or an array of documents. Thus, a typical document and a collection may be as follows:

CRUD1
Figure 1: The document/collection connection

CRUD in a Mongo Shell

Before going into Java code, let's first walk through CRUD operations in the mongo shell. Once MongoDB has been installed properly (see installation instructions), it provides an interactive shell called mongo. This shell can be invoked when required to directly interact with the database. The core database process, a daemon called mongod, must be up and running by invoking the mongo console. It can be executed as follows (unless mongod is already running):

mongod --port 27017 -dbpath /usr/local/db/mongodb

The number 27017 signifies the default port number of MongoDB and the path is where the actual database files are kept.

Start the console. Because no user is defined initially, we shall create one subsequently. Until then, simply open the console.

mongo

List the name of an available database:

>show dbs

Create a database administrator:

>db.createUser({
   user: "mano"
   pwd: "abc123"
   roles: [{
      role: "userAdminAnyDatabase"
      db: "admin"
      }]
   })

Restart mongod to reflect the changes as

mongod --auth --config /usr/local/etc/mongod.conf

Now, log in to the mongo shell as follows (change 'user' and 'abc123' according to your choice):

mongo -u user -p abc123 --authenticationDatabase admin

Once logged in, create the mydb database. This database shall contain a document collection which, in our case, is library.

>use mydb

Create Document

>db.library.insertOne({
   "title": "Discrete Mathematics",
   "isbn": "321-543-987",
   "authors": ["Kolman", "Busby", "Ross"],
   "category": ["discrete math", "math"]
})

Read Document

>db.library.find()
>db.library.find({category="math"})
>db.library.find({category="math", author="coleman"})

Update Document

>db.library.updateOne({ isbn: "123-456-789"},
   {$set:{title:"Compiler Design"}},{upsert:false})

Delete Document

>db.library.deleteOne({isbn:"111-222-333"})

Given, the preceding are very rudimentary CRUD operations executed from a mongo shell. Now, let's see how we can achieve the same CRUD effect through Java code.

CRUD Application in Java

It is pretty simple to code a rudimentary CRUD implementation in Java. Before delving into the code, download the JDBC driver and include the JAR file in the project build path, or follow the installation guide.

Observe that the code, in essence, is somewhat similar to database access in a relational model, although the underlying principle is very different.

package org.mano.example;

import java.util.Arrays;
import java.util.List;

import org.bson.Document;

import com.mongodb.Block;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.mongodb.client.FindIterable;

public class CRUD {

   private final static String HOST = "localhost";
   private final static int  PORT = 27017;
   private final static String DATABASE = "mydb";
   private final static String USER = "user";
   private final static String PASSWORD = "abc123";

   private MongoCredential mongoCredential;
   private MongoClient mongoClient;

   public CRUD() {
      mongoCredential = MongoCredential.createCredential
         (USER, DATABASE, PASSWORD.toCharArray());
      mongoClient = new MongoClient(new ServerAddress
         (HOST, PORT), Arrays.asList(mongoCredential));
   }

   public void create(String title, String isbn,
         List<String> authors, List<String> category) {
      try {
         mongoClient.getDatabase(DATABASE)
         .getCollection("library").insertOne(new Document()
         .append("tite", title).append("isbn", isbn)
         .append("authors", authors).append("category", category));
      } catch (Exception ex) {
         System.out.println(ex.getMessage());
      }
   }

   public void readAll() {
      try {
         FindIterable<Document> iter = mongoClient
            .getDatabase(DATABASE)
            .getCollection("library").find();

         iter.forEach(new Block<Document>() {
            @Override
            public void apply(Document doc) {
               System.out.println(doc);
            }
         });

      } catch (Exception ex) {
          System.out.println(ex.getMessage());
      }
   }

   public void updateCategory(String isbn, List<String> category) {

      try {
         mongoClient.getDatabase(DATABASE).getCollection("library")
         .updateOne(new Document("isbn", isbn),
         new Document("$set", new Document("category", category)));

      } catch (Exception ex) {
         System.out.println(ex.getMessage());
      }
   }

   public void delete(String isbn) {

      try {
         mongoClient.getDatabase(DATABASE).getCollection("library")
         .deleteOne(new Document("isbn", isbn));

      } catch (Exception ex) {
         System.out.println(ex.getMessage());
      }
    }

}


package org.mano.example;

import java.util.Arrays;

public class MongoDBCRUDExample {
   public static void main(String[] args) {
      CRUD c=new CRUD();
      c.readAll();
      c.create("Introduction to Software Engineering", "102-304-506",
         Arrays.asList("Jalote", "Ansari"),
         Arrays.asList("software", "software engineering"));
      c.create("Numerical Analysis", "999-888-777",
         Arrays.asList("Moulah", "Kabir"),
         Arrays.asList("math", "numerical"));
      c.readAll();
      c.updateCategory("999-888-777",
         Arrays.asList("mathematics","numerical", "computation"));
      c.readAll();
      c.delete("102-304-506");
      c.readAll();
   }
}
Note: Refer to the MongoDB CRUD guide for further details on the intricacies involved in Java implementation.

Conclusion

The article tried to give you a hands-on example of how to leverage Java and MongoDB with the help of a CRUD example without delving into much conceptual detail. The JDBC API library is highly intuitive and quite straightforward in dealing with connectivity as well as data manipulation through API functions. The intuitive appeal does not get diminished at all even as we go deeper into the complexities of a CRUD application. We shall see some aspects of it in the next few articles.


Tags: Java, NoSQL, MongoDB, database, JDBC, API, shell, NoSQL technology, CRUD, BSON, Mongo




Comment and Contribute

 


(Maximum characters: 1200). You have characters left.

 

 


Enterprise Development Update

Don't miss an article. Subscribe to our newsletter below.

Sitemap | Contact Us

Thanks for your registration, follow us on our social networks to keep up-to-date
Rocket Fuel