Spring Data working with MongoDB doing CRUD operations

MongoDB is a cross-platform, document oriented database that provides, high performance, high availability, and easy scalability. MongoDB works on concept of collection and document.

Database

Database is a physical container for collections. Each database gets its own set of files on the file system. A single MongoDB server typically has multiple databases.

Collection

Collection is a group of MongoDB documents. It is the equivalent of an RDBMS table. A collection exists within a single database. Collections do not enforce a schema. Documents within a collection can have different fields. Typically, all documents in a collection are of similar or related purpose.

Document

A document is a set of key-value pairs. Documents have dynamic schema. Dynamic schema means that documents in the same collection do not need to have the same set of fields or structure, and common fields in a collection's documents may hold different types of data.
Below given table shows the relationship of RDBMS terminology with MongoDB.

What is Spring Data - Document?

The Spring Data Document (or DATADOC) framework makes it easy to write Spring applications that use a Document store by eliminating the redundant tasks and boiler place code required for interacting with the store through Spring's excellent infrastructure support.

Source: Spring Datastore Document - Reference Documentation
In a nutshell MongoDB uses JSON instead of SQL There's no static schema to create. All schemas are dynamic, meaning you create them on-the-fly. You can try a real-time online shell for MongoDB at http://try.mongodb.org/. Visit the official MongoDB site for a thorough discussion.

You even insert MondoDB logs on production into Elasticsearch
Lets Start with an Example in Eclipse:
 
Jars Used

1)applicationContext.xml(copy it in class plath i.e. src folder of eclipse java project)

<?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"
    xsi:schemaLocation="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">

    <bean id="natureRepository"
        class="com.raamji.src.NatureRepositoryImpl">
        <property name="mongoTemplate" ref="mongoTemplate" />
    </bean>

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

    <!-- Factory bean that creates the Mongo instance -->
    <bean id="mongo" class="org.springframework.data.mongodb.core.MongoFactoryBean">
        <property name="host" value="ind-asingh" />
        <property name="port" value="27017" />
    </bean>

    <!-- Activate annotation configured components -->
    <context:annotation-config />

    <!-- Scan components for annotations within the configured package -->
    <context:component-scan base-package="com.raamji.src">
        <context:exclude-filter type="annotation"
            expression="org.springframework.context.annotation.Configuration" />
    </context:component-scan>

</beans>


2)MongoTest.java(This is the file to start with i.e. class having main program)
//You can uncomment the code here and see more advanced functioning.

package com.raamji.src;

import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;



public class MongoTest {

    public static void main(String[] args) {

        ConfigurableApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");

        Repository repository = context.getBean(NatureRepositoryImpl.class);

        // cleanup collection before insertion
        repository.dropCollection();

        // create collection
        repository.createCollection();

        repository.saveObject(new Tree("1", "Apple Tree", 10));

        System.out.println("1. " + repository.getAllObjects());

        repository.saveObject(new Tree("2", "Orange Tree", 3));

        System.out.println("2. " + repository.getAllObjects());

    //    System.out.println("Tree with id 1" + repository.getObject("1"));

        //repository.updateObject("1", "Peach Tree");

        //System.out.println("3. " + repository.getAllObjects());

        //repository.deleteObject("2");

        //System.out.println("4. " + repository.getAllObjects());
    }
}

3) Interface

package com.raamji.src;

import java.util.List;

import com.mongodb.WriteResult;

public interface Repository<T> {

    public List<T> getAllObjects();

    public void saveObject(T object);

    public T getObject(String id);

    public WriteResult updateObject(String id, String name);

    public void deleteObject(String id);

    public void createCollection();

    public void dropCollection();
}
4)Implementing Class
package com.raamji.src;

import java.util.List;

import org.springframework.data.mongodb.core.MongoTemplate;
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.mongodb.WriteResult;

public class NatureRepositoryImpl implements Repository<Tree> {

    MongoTemplate mongoTemplate;

    public void setMongoTemplate(MongoTemplate mongoTemplate) {
        this.mongoTemplate = mongoTemplate;
    }

    /**
     * Get all trees.
     */
    public List<Tree> getAllObjects() {
        return mongoTemplate.findAll(Tree.class);
    }

    /**
     * Saves a {@link Tree}.
     */
    public void saveObject(Tree tree) {
        mongoTemplate.insert(tree);
    }

    /**
     * Gets a {@link Tree} for a particular id.
     */
    public Tree getObject(String id) {
        return mongoTemplate.findOne(new Query(Criteria.where("id").is(id)), Tree.class);
    }

    /**
     * Updates a {@link Tree} name for a particular id.
     */
    public WriteResult updateObject(String id, String name) {
        return mongoTemplate.updateFirst(new Query(Criteria.where("id").is(id)), Update.update("name", name), Tree.class);
    }

    /**
     * Delete a {@link Tree} for a particular id.
     */
    public void deleteObject(String id) {
        mongoTemplate.remove(new Query(Criteria.where("id").is(id)), Tree.class);
    }

    /**
     * Create a {@link Tree} collection if the collection does not already
     * exists
     */
    public void createCollection() {
        if (!mongoTemplate.collectionExists(Tree.class)) {
            mongoTemplate.createCollection(Tree.class);
        }
    }

    /**
     * Drops the {@link Tree} collection if the collection does already exists
     */
    public void dropCollection() {
        if (mongoTemplate.collectionExists(Tree.class)) {
            mongoTemplate.dropCollection(Tree.class);
        }
    }

}

5)Model class, using MongoTemplate
MongoTemplate is the place to look for accessing functionality such as incrementing counters or ad-hoc CRUD operations. MongoTemplate also provides callback methods so that it is easy for you to get a hold of the low level API artifacts such as org.mongo.DB to communicate directly with MongoDB.


package com.raamji.src;

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

@Document
public class Tree {

    @Id
    private String id;

    private String name;

    private String category;

    private int age;

    public Tree(String id, String name, int age) {
        this.id = id;
        this.name = name;
        this.age = age;
    }

    public String getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    public String getCategory() {
        return category;
    }

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

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Person [id=" + id + ", name=" + name + ", age=" + age
                + ", category=" + category + "]";
    }
}
Check my more data on YouTube or on Udemy.
//result into


No comments:

Post a Comment