Spring 4 MongoDB Example (MongoTemplate CRUD)

By Yashwant Chavan, Views 194113, Date 29-Dec-2016

In this tutorial, You will learn how to connect to MongoDB database and perform the different CRUD operations using Spring 4 and MongoTemplate. We have used Java base configurations to load the MongoTemplate. Refer below steps to accessing data with MongoDB using Spring 4.

tags spring

Spring 4 Eclipse project set up

Spring 4 mongoDB Example Example - Eclipse project setup

Tools and Technologies

  1. Apache Maven 3.0.4
  2. JDK 1.8
  3. Spring core, Spring context, spring context support and spring context (4.1.4.RELEASE)
  4. MongoDB 3.3.12

pom.xml

As we are using Maven project. Let's define the spring 4 specific maven dependencies.

<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.technicalkeeda</groupId>
    <artifactId>Spring4Examples</artifactId>
    <packaging>jar</packaging>
    <version>1.0</version>
    <name>Spring4Examples</name>
    <description></description>
    <build>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <properties>
        <spring.version>4.3.5.RELEASE</spring.version>
    </properties>

    <dependencies>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-mongodb</artifactId>
            <version>1.9.5.RELEASE</version>
        </dependency>

    </dependencies>
</project>

Car Pojo

This is simple Car pojo class which contains different attributes like id, brand and model. @Document annotation is used at the class level, Which identifies a domain object / pojo is going to be persisted to MongoDB database. You can specify the name of the collection e.g. cars

@Id annotation used at the field level to mark it for identity purpose.

package com.technicalkeeda.bean;

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

@Document(collection = "cars")
public class Car {
    @Id
    private String id;
    private String brand;
    private String model;

    public Car(String brand, String model) {
        super();
        this.brand = brand;
        this.model = model;
    }

    public String getId() {
        return id;
    }

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

    public String getBrand() {
        return brand;
    }

    public void setBrand(String brand) {
        this.brand = brand;
    }

    public String getModel() {
        return model;
    }

    public void setModel(String model) {
        this.model = model;
    }

    @Override
    public String toString() {
        StringBuilder str = new StringBuilder();
        str.append("Id:- " + getId() + ", Brand:- " + getBrand() + ", Model:- " + getModel());
        return str.toString();
    }

}

Spring 4 Application Configuration (JavaConfig)

@Configuration annotation imports the Spring configuration. @Configuration objects are managed as Spring beans within the container, imported configurations are used to injected using @Autowired or @Inject.

@ComponentScan is equivalent to <context:component-scan base-package="..." used to lookup the beans and components classes in the spring context.

To declare a bean, simply annotate a method with the @Bean annotation. When JavaConfig encounters such a method, it will execute that method and register the return value as a bean within a BeanFactory.

Here we have registered MongoDbFactory and MongoTemplate beans.

package com.technicalkeeda.configuration;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.authentication.UserCredentials;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoDbFactory;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;

import com.mongodb.MongoClient;

@Configuration
@ComponentScan(basePackages = "com.technicalkeeda")
public class ApplicationConfig {

    @Bean
    public MongoDbFactory mongoDbFactory() throws Exception {
        MongoClient mongoClient = new MongoClient("localhost", 27017);
        UserCredentials userCredentials = new UserCredentials("", "");
        return new SimpleMongoDbFactory(mongoClient, "technicalkeeda", userCredentials);
    }

    @Bean
    public MongoTemplate mongoTemplate() throws Exception {
        MongoTemplate mongoTemplate = new MongoTemplate(mongoDbFactory());
        return mongoTemplate;
    }

}

CarService

Creates CarService interface along with different methods.

  1. Create new Car document.
  2. Update Car document.
  3. Delete Car document.
  4. Delete all Car documents.
  5. Return Car identified by id.
  6. Returns all Car documents
package com.technicalkeeda.services;

import java.util.List;

import com.technicalkeeda.bean.Car;

public interface CarService {

    public void create(Car car);

    public void update(Car car);

    public void delete(Car car);

    public void deleteAll();

    public Car find(Car car);

    public List < Car > findAll();
}

CarServiceImpl

Mark CarServiceImpl class as "carService" using @Service annotation. Use @Autowired annotation to autowire CarDao bean.

package com.technicalkeeda.services;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.technicalkeeda.bean.Car;
import com.technicalkeeda.dao.CarDao;

@Service("carService")
public class CarServiceImpl implements CarService {

    @Autowired
    CarDao carDao;

    public void create(Car car) {
        carDao.create(car);
    }

    public void update(Car car) {
        carDao.update(car);
    }

    public void delete(Car car) {
        carDao.delete(car);
    }

    public List < Car > findAll() {
        return carDao.findAll();
    }

    public Car find(Car car) {
        return carDao.find(car);
    }

    public void deleteAll() {
        carDao.deleteAll();
    }
}

CarDao Interface

Create CarDao interface along with Car CRUD operation methods.

package com.technicalkeeda.dao;

import java.util.List;

import com.technicalkeeda.bean.Car;

public interface CarDao {

    public void create(Car car);

    public void update(Car car);

    public void delete(Car car);

    public void deleteAll();

    public Car find(Car car);

    public List < Car > findAll();
}

CarDao implementation

CarDaoImpl marked with @Repository annotation, It allows the component scanning to find and configure the respected DAO. @Autowired mongoTemplate to perform the CRUD operation on Car document.

package com.technicalkeeda.dao;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
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.stereotype.Repository;

import com.technicalkeeda.bean.Car;

@Repository
@Qualifier("carDao")
public class CarDaoImpl implements CarDao {

    @Autowired
    MongoTemplate mongoTemplate;

    final String COLLECTION = "cars";

    public void create(Car car) {
        mongoTemplate.insert(car);
    }

    public void update(Car car) {
        mongoTemplate.save(car);
    }

    public void delete(Car car) {
        mongoTemplate.remove(car);
    }

    public void deleteAll() {
        mongoTemplate.remove(new Query(), COLLECTION);
    }

    public Car find(Car car) {
        Query query = new Query(Criteria.where("_id").is(car.getId()));
        return mongoTemplate.findOne(query, Car.class, COLLECTION);
    }

    public List < Car > findAll() {
        return (List < Car > ) mongoTemplate.findAll(Car.class);
    }

}

App.java

To create standalone Spring Application Context, We are using AnnotationConfigApplicationContext which helps to register all the beans generated by the configuration class (@Configuration) at Spring runtime.

Use AbstractApplicationContext.getBean(String name) method is used to get bean object( "carService") from Spring application context.

Once you get the "carService" instance perform different CRUD operations.

package com.technicalkeeda.test;

import java.util.List;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.AbstractApplicationContext;

import com.technicalkeeda.bean.Car;
import com.technicalkeeda.configuration.ApplicationConfig;
import com.technicalkeeda.services.CarService;

public class App {

    public static void main(String args[]) {

        AbstractApplicationContext context = new AnnotationConfigApplicationContext(ApplicationConfig.class);
        CarService carService = (CarService) context.getBean("carService");
        // Delete All cars
        carService.deleteAll();

        Car polo = new Car("Volkswagen", "Polo");
        carService.create(polo);

        Car jetta = new Car("Volkswagen", "Jetta");
        carService.create(jetta);

        Car swift = new Car("Maruti Suzuki", "Swift");
        carService.create(swift);

        Car ertiga = new Car("Maruti Suzuki", "Ertiga");
        carService.create(ertiga);

        Car i10 = new Car("Hyundai", "i10");
        carService.create(i10);

        Car i20 = new Car("Hyundai", "i20");
        carService.create(i20);

        System.out.println("Find One:- " + carService.find(swift));

        System.out.println("Find All!!");

        List < Car > cars = carService.findAll();
        for (Car car: cars) {
            System.out.println(car);
        }
        System.out.println();
        carService.delete(swift);

        System.out.println();
        i10.setModel("i10 Nxt");
        carService.update(i10);

        System.out.println("Find All After Update!!");

        cars = carService.findAll();
        for (Car car: cars) {
            System.out.println(car);
        }

        context.close();
    }

}

output

SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
Find One:- Id:- 5864faafd277183fddc7f36f, Brand:- Maruti Suzuki, Model:- Swift
Find All!!
Id:- 5864faafd277183fddc7f36d, Brand:- Volkswagen, Model:- Polo
Id:- 5864faafd277183fddc7f36e, Brand:- Volkswagen, Model:- Jetta
Id:- 5864faafd277183fddc7f36f, Brand:- Maruti Suzuki, Model:- Swift
Id:- 5864faafd277183fddc7f370, Brand:- Maruti Suzuki, Model:- Ertiga
Id:- 5864faafd277183fddc7f371, Brand:- Hyundai, Model:- i10
Id:- 5864faafd277183fddc7f372, Brand:- Hyundai, Model:- i20


Find All After Update!!
Id:- 5864faafd277183fddc7f36d, Brand:- Volkswagen, Model:- Polo
Id:- 5864faafd277183fddc7f36e, Brand:- Volkswagen, Model:- Jetta
Id:- 5864faafd277183fddc7f370, Brand:- Maruti Suzuki, Model:- Ertiga
Id:- 5864faafd277183fddc7f371, Brand:- Hyundai, Model:- i10 Nxt
Id:- 5864faafd277183fddc7f372, Brand:- Hyundai, Model:- i20

MongoDB Shell output

> use technicalkeeda
switched to db technicalkeeda
> show collections
articles_bkp
cars
person
system.indexes
system.profile
> db.cars.find().pretty()
{
        "_id" : ObjectId("5864faafd277183fddc7f36d"),
        "_class" : "com.technicalkeeda.bean.Car",
        "brand" : "Volkswagen",
        "model" : "Polo"
}
{
        "_id" : ObjectId("5864faafd277183fddc7f36e"),
        "_class" : "com.technicalkeeda.bean.Car",
        "brand" : "Volkswagen",
        "model" : "Jetta"
}
{
        "_id" : ObjectId("5864faafd277183fddc7f370"),
        "_class" : "com.technicalkeeda.bean.Car",
        "brand" : "Maruti Suzuki",
        "model" : "Ertiga"
}
{
        "_id" : ObjectId("5864faafd277183fddc7f371"),
        "_class" : "com.technicalkeeda.bean.Car",
        "brand" : "Hyundai",
        "model" : "i10 Nxt"
}
{
        "_id" : ObjectId("5864faafd277183fddc7f372"),
        "_class" : "com.technicalkeeda.bean.Car",
        "brand" : "Hyundai",
        "model" : "i20"
}
>
Yashwant Chavan

Yashwant Chavan

Hi there! I am founder of technicalkeeda.com and programming enthusiast. My skills includes Java,J2EE, Spring Framework, Nodejs, PHP and lot more. If you have any idea that you would want me to develop? Lets connect: yashwantchavan@gmail.com