Tuesday 26 June 2012

Java: MongoDB simple example


MongoDB - is an open source document-oriented NoSQL database system. Next I will create simple servlet example that's uses MongoDB. 


Installation

  1. Download  MongoDB (ex. Windows unzip it  c:\mongo)
  2. Create folder /data/db (ex. Windows c:\data\db )
  3. To start mongo, use  mongod from bin folder (ex. Windows c:\mongo\bin\mongod.exe )
  4. To use Mongo in java you need java driver to be included
Coding

Form
<h1> Add new book </h1>
<form action="SaveData" method="POST">
    Name:  <input name="name" size="20" />
    Year:   <input name="year"  size="6" />
    Language: <input name="language  size="20" />
    Author: <input name="author"  size="20" />
    <input type="submit"   value="Add">
</form>

Servlet
@WebServlet("/SaveData")
public class SaveData extends HttpServlet {
 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  try{
        
         DBCollection bookCollection;      
         // init  
         Mongo mongo = new Mongo();
         DB db = mongo.getDB("booksDB");
         bookCollection = db.getCollection("books");
         if (bookCollection == null) {
             bookCollection = db.createCollection("books", null);
         }
         // create    
         Book book = new Book(); 
         book.setAuthor(request.getParameter("author"));
         book.setLanguage(request.getParameter("language"));
         book.setName(request.getParameter("name"));
         book.setYear(Integer.parseInt(request.getParameter("year")));
                  
        BasicDBObject doc = book.toDBObject();
        bookCollection.insert(doc);

        // display
        List<Book> books = new ArrayList<Book>();           
        DBCursor cursor = bookCollection.find();
         while (cursor.hasNext()) {
             DBObject dbo = cursor.next();
             Book b = Book.fromDBObject(dbo);
             System.out.println(b.getName());
             books.add(b);
         }
        // returning data         
        request.setAttribute("books", books);
        request.getRequestDispatcher("showData.jsp").forward(request, response);
  } catch(Exception e){
   e.printStackTrace();
  }
 }
}
book bean:
public class Book {

 private String name;
 private String author;
 private String language;
 private int year;
 
 public BasicDBObject toDBObject() {
  BasicDBObject document = new BasicDBObject();
  document.put("name", name);
  document.put("year", year);
  document.put("language", language);
  document.put("author", author);
  return document;
 }

 public static Book fromDBObject(DBObject document) {
  Book b = new Book();
  b.name = (String) document.get("name");
  b.year = (Integer) document.get("year");
  b.language = (String) document.get("language");
  b.author = (String) document.get("author");
  return b;
 }
      //getters, setters...
}

References:
Doc
SQL to Mongo Mapping Chart
Tutorial official

1 comment: