Skip to main content

Initial Setup for Spring with MongoDb in Eclipse with Maven


Here , we show you how to configure mongodb and maven in eclipse on windows to starting with spring projects.


Tools and technologies used :


  1. Spring Data MongoDB – 1.2.0.RELEASE
  2. Spring Core – 3.2.2.RELEASE
  3. Java Mongo Driver – 2.11.0
  4. Eclipse – 4.2
  5. JDK – 1.7
  6. Maven – 3.0.3

MongoDb Installation

Download MongoDB from official MongoDB website. Choose Windows 32 bits or 64 bits.In Windows Explorer, locate the downloaded MongoDB .msi file, which typically is located in the default Downloads folder. Double-click the .msi file. A set of screens will appear to guide you through the installation process. 
You may specify an installation directory if you choose the “Custom” installation option. These instructions assume that you have installed MongoDB to C:\mongodb.
MongoDB is self-contained and does not have any other system dependencies. You can run MongoDB from any folder you choose. You may install MongoDB in any folder (e.g.D:\test\mongodb).

1.Set up the MongoDB environment

MongoDB requires a data directory to store all data. MongoDB’s default data directory path is\data\db. Create this folder using the following commands from a Command Prompt:

md  \data\db
You can specify an alternate path for data files using the --dbpath option to mongod.exe, for example:
C:\mongodb\bin\mongod.exe --dbpath "d:\test\mongo db data"

2.Start MongoDB



To start MongoDB, run mongod.exe. For example, from the Command Prompt:
C:\mongodb\bin\mongod.exe
This starts the main MongoDB database process. The waiting for connections message in the console output indicates that the mongod.exe process is running successfully.
Depending on the security level of your system, Windows may pop up a Security Alert dialog box about blocking “some features” of C:\mongodb\bin\mongod.exe from communicating on networks. All users should select Private Networks, such as my home or worknetwork and click Allow access. For additional information on security and MongoDB, please see the Security Documentation.

3.Connect to MongoDB

To connect to MongoDB through the mongo.exe shell, open another Command Prompt:
C:\mongodb\bin\mongo.exe
If you want to develop applications using .NET, see the documentation of C# and MongoDB for more information.For more details go to here, follow the instruction.

Maven Installation

Maven is a Java tool, so you must have Java installed in order to proceed. Maven is a tool  which can be used for building and managing of any Java based project. This tool is developed by Apache. Here you will find initial setup for java project with maven in eclipse.
If you beginner for maven , please got to here to understand the how to build java project with maven.


Maven Eclipse plugin installation step by step:


Open Eclipse IDE


Click Help -> Install New Software…
Click Add button at top right corner


At pop up: fill up Name as "M2Eclipse" and Location as




First Stpes to add maven plugin.jpg


Now click on Next


After that installation would be started.


Another way to install Maven plug-in for Eclipse:
Open Eclipse
Go to Help -> Eclipse Marketplace
Search by Maven
Click "Install" button at "Maven Integration for Eclipse" section
Follow the instruction step by step


After successful installation do the followings in Eclipse:


Go to Window --> Preferences
Observe, Maven is enlisted at left panel


Finally,


Click on an existing project
Select Configure -> Convert to Maven Project

Starting Spring Project with MongoDb in Eclipse with Maven


In this tutorial, we show you how to use “SpringData for MongoDB” framework, to perform CRUD operations in MongoDB, via Spring’s annotation and XML schema.


1.Steps to create project


Open Eclipse IDE
Click on New -> Click on Project -> Click on Maven Project…


In the popup new maven project select the option as your choice , In my I select the both option shown as following snapshot.


Step 1 Create Spring projects.jpg

After that In project explorer add your required details as like following screen and the project related parameters .


In my case I use following details.


groupId : com.santosh.core
artifactId : SpringMongoDBFirst
name : SpringMongoDBFirst


Step 2 Create Spring projects.jpg

Step 3 Create Spring projects.jpg


A classic Maven’s style Java project directory structure.


Step 4 Spring Project Architecture.jpg

2.Dependency Management in pom.xml

<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>com.santosh.core</groupId>
 <artifactId>SpringMongoDBFirst</artifactId>
 <version>0.0.1-SNAPSHOT</version>
 <name>SpringMongoDBFirst</name>
 
 <properties>


<!-- Generic properties -->
<java.version>1.7</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>


<!-- Spring -->
<spring-framework.version>4.0.3.RELEASE</spring-framework.version>
<spring-data-mongodb.version>1.5.2.RELEASE</spring-data-mongodb.version>


<!-- Logging -->
<logback.version>1.0.13</logback.version>
<slf4j.version>1.7.5</slf4j.version>


</properties>
<dependencies>
<!-- Spring and Transactions -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring-framework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring-framework.version}</version>
</dependency>
<dependency>
    <groupId>org.springframework.data</groupId>
    <artifactId>spring-data-mongodb</artifactId>
    <version>${spring-data-mongodb.version}</version>
  </dependency>
 
<!-- Logging with SLF4J & LogBack -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>${logback.version}</version>
<scope>runtime</scope>
</dependency>


</dependencies>
</project>

3. Spring Configuration, Annotation and XML



Here, we show you two ways to configure Spring data and connect to MongoDB, via annotation and XML schema.Official reference for the spring with mongodb are here.


SpringMongoConfig.java


package com.santosh.config;


import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.config.AbstractMongoConfiguration;


import com.mongodb.Mongo;
import com.mongodb.MongoClient;


@Configuration
public class SpringMongoConfig extends AbstractMongoConfiguration {


@Override
public String getDatabaseName() {
return "test";
}


@Override
@Bean
public Mongo mongo() throws Exception {
return new MongoClient("127.0.0.1");
}
}


XML Schema are as follows : SpringConfig.xml


<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">


<mongo:mongo host="127.0.0.1" port="27017" />
<mongo:db-factory dbname="test" />


<bean id="mongoTemplate"class="org.springframework.data.mongodb.core.MongoTemplate">
<constructor-arg name="mongoDbFactory" ref="mongoDbFactory" />
</bean>


</beans>


User Model are as folllows : User.java


package com.santosh.model;


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


@Document(collection = "users")
public class User {


@Id
private String id;


String username;


String password;


public String getId() {
return id;
}


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


public String getUsername() {
return username;
}


public void setUsername(String username) {
this.username = username;
}


public String getPassword() {
return password;
}


public void setPassword(String password) {
this.password = password;
}


public User(String username, String password) {
super();
this.username = username;
this.password = password;
}


@Override
public String toString() {
return "User [id=" + id + ", username=" + username + ", password=" + password + "]";
}
}


For the operation on database use the following class : App.java


package com.santosh.core;


import java.util.List;


import org.springframework.context.ApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;


import com.santosh.model.User;
//import org.springframework.context.support.GenericXmlApplicationContext;


public class App {


public static void main(String[] args) {


// For XML
ApplicationContext ctx = new GenericXmlApplicationContext("SpringConfig.xml");


// For Annotation
//ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringMongoConfig.class);
MongoOperations mongoOperation = (MongoOperations) ctx.getBean("mongoTemplate");


User user = new User("santosh", "santosh123");


// save
mongoOperation.save(user);


// now user object got the created id.
System.out.println("1. user : " + user);


// query to search user
Query searchUserQuery = new Query(Criteria.where("username").is("santosh"));


// find the saved user again.
User savedUser = mongoOperation.findOne(searchUserQuery, User.class);
System.out.println("2. find - savedUser : " + savedUser);


// update password
mongoOperation.updateFirst(searchUserQuery, Update.update("password", "santosh123"),
User.class);


// find the updated user object
User updatedUser = mongoOperation.findOne(
new Query(Criteria.where("username").is("santosh")), User.class);


System.out.println("3. updatedUser : " + updatedUser);


// delete
//mongoOperation.remove(searchUserQuery, User.class);


// List, it should be empty now.
List<User> listUser = mongoOperation.findAll(User.class);
System.out.println("4. Number of user = " + listUser.size());


}


}


Final structure of project in eclipse are like as follows :


Step 6 Spring Project Architecture.jpg

Download source code from here.

4.Build Application


Right click on project and select Run as -> Maven Install
After getting success on console right click on App.java and select
Run as -> Java Application


You get following output in your console
15:12:13.605 [main] DEBUG o.s.data.mongodb.core.MongoDbUtils - Getting Mongo Database name=[test]
1. user : User [id=5593b5f54e2201c733ccf794, username=santosh, password=santosh123]
15:12:13.622 [main] DEBUG o.s.data.mongodb.core.MongoTemplate - findOne using query: { "username" : "santosh"} fields: null for class: class com.santosh.model.User in collection: users
15:12:13.624 [main] DEBUG o.s.data.mongodb.core.MongoDbUtils - Getting Mongo Database name=[test]
15:12:13.625 [main] DEBUG o.s.data.mongodb.core.MongoTemplate - findOne using query: { "username" : "santosh"} in db.collection: test.users
2. find - savedUser : User [id=5593b5f54e2201c733ccf794, username=santosh, password=santosh123]
15:12:13.638 [main] DEBUG o.s.data.mongodb.core.MongoDbUtils - Getting Mongo Database name=[test]
15:12:13.643 [main] DEBUG o.s.data.mongodb.core.MongoTemplate - Calling update using query: { "username" : "santosh"} and update: { "$set" : { "password" : "santosh123"}} in collection: users
15:12:13.646 [main] DEBUG o.s.data.mongodb.core.MongoTemplate - findOne using query: { "username" : "santosh"} fields: null for class: class com.santosh.model.User in collection: users
15:12:13.646 [main] DEBUG o.s.data.mongodb.core.MongoDbUtils - Getting Mongo Database name=[test]
15:12:13.647 [main] DEBUG o.s.data.mongodb.core.MongoTemplate - findOne using query: { "username" : "santosh"} in db.collection: test.users
3. updatedUser : User [id=5593b5f54e2201c733ccf794, username=santosh, password=santosh123]
15:12:13.649 [main] DEBUG o.s.data.mongodb.core.MongoDbUtils - Getting Mongo Database name=[test]

4. Number of user = 1

Comments

Popular posts from this blog

What exactly means MVW design pattern ?

What is a MVW framework? The abbreviation stands for 'Model - View - Whatever'.  Well there are many different JavaScript frameworks available , all invented for the same purpose. They all try to separate the presentation logic from the business logic where JavaScript holds the model and logic, and html the presentation layer. Quick overview : You can change the model without changing the view and vice-versa Unit testing is easy These are the core benefits of using such a framework. By separating presentation and business logic changes to the code are easier to implement and take less time. Another benefit is that code can be reused from a controller thus saving more time. Angularjs makes the code also shorter in comparison to other frameworks, which improves code stability. Less code means minor potential for bugs. For several years +AngularJS was closer to MVC (or rather one of its client-side variants), but over time and thanks to many refactorings

File Upload & Download With ng-cordova File Transfer Plugin In Ionic Framework

Using the AngularJS extension set , ngCordova , with Ionic Framework and the Apache Cordova File Transfer plugin, you can easily upload files to a remote server and download files from a remote server. 1.Create the project ionic start Test blank cd Test ionic platform add android 2.Add Plugin org.apache.cordova.file-transfer https://github.com/apache/cordova-plugin-file-transfer This plugin allows you to upload and download files. This plugin defines global FileTransfer, FileUploadOptions Constructors. Although in the global scope, they are not available until after the deviceready event . Installation cordova plugin add cordova plugin add cordova-plugin-file-transfer     2.    org.apache.cordova.file             https://github.com/apache/cordova-plugin-file             This plugin implements a File API allowing read/write access to files residing on the    device.             Installation cordova plugin add cordova-pl

Steps To Create Cordova Plugin

Introduction A plugin is a package of injected code that allows the Cordova webview within which the app renders to communicate with the native platform on which it runs. Plugins comprise a single JavaScript interface along with corresponding native code libraries for each supported platform. Due to following reason, we will go for plugin development To get the native capabilities of the device in the cordova based app Build the common functionality across the number of Cordova application(Reusability) Prerequisites For the creation of plugin you need to install plugman . npm install -g plugman Plugin Structure Decide Plugin ID & Name The plugin ID should be unique Plugin name should follow the convention “cordova.plugin.[your.plugin.name]” Create the structure Use the following command to create the plugin with plugin ID “cordova.plugin.test” and name “Test”. plugman create --name Test --