No SQL DB MongoDB Introduction

Standard

Recently i seen no sql database . I was thought it’s some new concept until i read the documentation .

When i read the documentation i found that its similar to lotus notes documents concept , But more advance for scalability or performance .

Basic concept is .

  1. A Database have have multiple collections .
  2. Collection have multiple Documents.
  3. Documents can have embedded documents.
  4. documents have multiple fields.
  5. Each document have unique id called _id field.

Difference between lotus notes is , louts notes don’t have multiple collections , not able to embedded document into documents .

I hope that is enough as beginning .

For installng mongo db in ubuntu iam using


sudo apt-get install mongodb

then start the service using


sudo mongod start

then again


mongo


I am using netbeans to create new Maven web project with following pom files.

Basic idea about project iam storing Employee data in Mongo DB and check in shell that data is available.

I use maven for dependency and building the war file and deploy into netbeans buil in tomcat 7.

Following the pom files for dependency .


<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">
<modelVersion>4.0.0</modelVersion>

<groupId>ed.ws</groupId>
<artifactId>mongospring</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>

<name>mongospring</name>
<url>http://maven.apache.org</url>

<dependencies>

<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>

<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.1</version>
<scope>provided</scope>
</dependency>

<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.8.2</version>
<scope>test</scope>
</dependency>

<!-- Spring framework -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>3.0.5.RELEASE</version>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>3.0.5.RELEASE</version>
</dependency>

<!-- mongodb java driver -->
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>2.5.2</version>
</dependency>

<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb</artifactId>
<version>1.0.0.M4</version>
</dependency>

<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>2.2</version>
</dependency>

</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.0.2</version>
<configuration>
<source>1.5</source>
<target>1.5</target>
</configuration>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>spring-snapshot</id>
<name>Spring Maven SNAPSHOT Repository</name>
<url>http://s3.amazonaws.com/maven.springframework.org/snapshot</url>
</repository>

<repository>
<id>spring-milestone</id>
<name>Spring Maven MILESTONE Repository</name>
<url>http://maven.springframework.org/milestone</url>
</repository>
</repositories>
</project>

Next Step iam going to setup spring MVC and Applications Context .
Application context iam using beans.xml .

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mongo="http://www.springframework.org/schema/data/mongo"
xsi:schemaLocation="http://www.springframework.org/schema/context

http://www.springframework.org/schema/context/spring-context-3.0.xsd


http://www.springframework.org/schema/data/mongo


http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd


http://www.springframework.org/schema/beans


http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

<!-- Scan components for annotations within the configured package -->
<context:component-scan base-package="edu.samples.repository">
<context:exclude-filter type="annotation" expression="org.springframework.context.annotation.Configuration"/>
</context:component-scan>
<context:annotation-config/>
<mongo:mongo  host="127.0.1.1" port="27017"/>

<mongo:db-factory id="mongoDbFactory" dbname="demo" mongo-ref="mongo" />

<bean id="template">
<constructor-arg name="mongoDbFactory" ref="mongoDbFactory"/>
</bean>

<bean/>

</beans>

Iam creating mongo db template in application context and annotate so it will auto inject into Contact Repository .
Iam creating Contact Repository to save Contact Object into Mongo Table.

Before insert into database , iam checking that collection available for entity name otherwise iam creating it .

Its not necessary that each entity type has one collection . One collection have multiple type of entity .

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package edu.samples.repository;

import edu.samples.mvc.basic.Contact;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Repository;

/**
*
* @author home
*/
@Repository
public class ContactRepository {
@Autowired
private MongoTemplate mongoTemplate;
public void insertContact(Contact contact) {

createPersonCollection();

//mongoTemplate.save(contact,"collections");

mongoTemplate.insert(contact);

}
public void createPersonCollection() {
if (!mongoTemplate.collectionExists(Contact.class)) {
mongoTemplate.createCollection(Contact.class);
}
}
}

Two way i can insert either use save or insert .
Save we can use collection name as parameter . Insert its use Entity class name for insert .
Following are my pojo for contact. @Document is base anotation. and @Id is id field .

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package edu.samples.mvc.basic;

import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;

/**
*
* @author home
*/
@Document
public class Contact {
private String name;
private String phone;
private String email;
private String department;
private String designation;

@Id
private String id;

public String getId() {
return id;
}

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

public String getDepartment() {
return department;
}

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

public String getDesignation() {
return designation;
}

public void setDesignation(String designation) {
this.designation = designation;
}

public String getEmail() {
return email;
}

public void setEmail(String email) {
this.email = email;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getPhone() {
return phone;
}

public void setPhone(String phone) {
this.phone = phone;
}

}

Moving forward the setup for mvc .
Setting up common servlet as follows .

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">

<!-- Scans the classpath of this application for @Components to deploy as beans -->
<context:component-scan base-package="edu.samples.mvc.basic" />

<!-- Configures the @Controller programming model -->
<mvc:annotation-driven />

<!-- Forwards requests to the "/" resource to the "welcome" view -->
<mvc:view-controller path="/" view-name="welcome"/>

<!-- Configures Handler Interceptors -->
<mvc:interceptors>
<!-- Changes the locale when a 'locale' request parameter is sent; e.g. /?locale=de -->
<bean />
</mvc:interceptors>

<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources/ directory -->
<mvc:resources mapping="/resources/**" location="/resources/" />

<!-- Saves a locale change using a cookie -->
<bean id="localeResolver" />

<!-- Application Message Bundle -->
<bean id="messageSource">
<property name="basename" value="/WEB-INF/messages/messages" />
<property name="cacheSeconds" value="0" />
</bean>

<!-- Resolves view names to protected .jsp resources within the /WEB-INF/views directory -->
<bean>
<property name="prefix" value="/WEB-INF/"/>
<property name="suffix" value=".jsp"/>
</bean>

</beans>

Iam using resources to keep my commong css and js files .
All other settings are commong for Spring MVC 3 setups. Nothing fancy .
next is controller code.

I am using /basic as url , to display and update contact details .

When post the /basic controller from front end , the contact Pojo already updated with value .

When calling insertContact method , it will insert the data into mongo db.

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package edu.samples.mvc.basic;

import edu.samples.repository.ContactRepository;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

/**
*
* @author home
*/
@Controller
@RequestMapping(value = "/basic")
public class BasicController {
@Autowired
ContactRepository repository;
private static final Logger logger = Logger.getLogger(BasicController.class);

@RequestMapping(method = RequestMethod.GET)
public String getCreateForm(Model model) {
logger.info("started basecontroller");
logger.debug("base controller debug");
model.addAttribute("testing");
model.addAttribute("contactbean", new Contact());
return "basic/basicForm";
}

@RequestMapping(method = RequestMethod.POST)
public String createContact(@ModelAttribute("contactbean")Contact contact, BindingResult result) {
System.out.println("started uploading" + contact.getName());

if (result.hasErrors()) {
for (ObjectError error : result.getAllErrors()) {
System.err.println("Error in uploading: " + error.getCode() + " - " + error.getDefaultMessage());
}
}
repository.insertContact(contact);
return "basic/basicForm";
}
}

I am using Contact pojo as front end pojo and back end pojo for inserting back to database .

Final one jsp page code .

<%--
Document   : basicForm
Created on : Oct 11, 2011, 9:03:28 PM
Author     : home
--%>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib uri="http://www.springframework.org/tags" prefix="s" %>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form" %>

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
<title>spring-mvc-showcase</title>
<link href="<c:url value="/resources/css/custom-theme/jquery-ui-1.8.16.custom.css" />" rel="stylesheet" type="text/css" />

<script type="text/javascript" src="<c:url value="/resources/js/jquery-1.6.2.min.js" />"></script>
<script type="text/javascript" src="<c:url value="/resources/js/jquery-ui-1.8.16.custom.min.js" />"></script>
<script type="text/javascript" src="<c:url value="/resources/js/jquery.ui.button.js" />"></script>
<script type="text/javascript" src="<c:url value="/resources/js/jquery.ui.core.js" />"></script>
<script type="text/javascript" src="<c:url value="/resources/js/jquery.ui.widget.js" />"></script>
<script>
$(document).ready(function() {
$("button").button();
});

</script>
<style type="text/css">
*{
margin:0;
padding:0;
font:bold 12px "Lucida Grande", Arial, sans-serif;
}
body {
padding: 10px;
}
#status{
width:250px;
padding:10px;
outline:none;
height:36px;
}

</style>
</head>
<body>
<form:form modelAttribute="contactbean" method="post" >
<h1>Its for saving Employee details back to MongoDB/h1>
<table>
<tr>
<td> <div> Your name </div></td>
<td>
<form:input path="name"/>
</br></td>
</tr>
<tr>
<td>  <div> Your email account </div></td>
<td>
<form:input path="email"/>
</br></td>
</tr>
<tr>
<td>

<div> Your mobile phone </div></td>
<td>
<form:input path="phone"/>
</td>
</tr>
<tr>
<td><div> Your Department </div></td>
<td>  <form:input path="department"/>
</td>
</tr>
<tr>
<td><div> Designation </div></td>
<td>  <form:input path="designation"/>
</td>
</tr>

</table>

<button>Click here to save</button>

</form:form>

</button>
</body>
</html>

Iam using jquery library . but i keep the library in the resources folder .
That functionality is new in spring MVC .
Now time to deploy the application in tomcat
Build the application and deploy in the tomcat using netbeans build it tomcat 7.
The front page looks like as follows and click on green button to save the data .

 

 

 

 

 

 

 

 

Once save the data , iam looking on shell to verify the data.
As we are create collection based on entity type , the collection name should be contact.

public void createPersonCollection() {
if (!mongoTemplate.collectionExists(Contact.class)) {
mongoTemplate.createCollection(Contact.class);
}
}

 

 

Finally result showing in the terminal

 

 

 

 

 

I hope its useful with spring MVC with Mongo DB with latest release .
If you have any comments please let me know

About these ads

2 thoughts on “No SQL DB MongoDB Introduction

  1. Pingback: Spring MVC With Mongo DB CRUDE Operations « Sjohn's Blog

  2. Pingback: SpringData MongoDB GeoSpatial Query « Sjohn's Blog

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s