Spring 4 MongoDB Repository Example

By Yashwant Chavan, Views 75853, Date 26-Dec-2016

In this tutorial, You will learn how to access MongoDB database using Spring 4 MongoRepository. Configure MongoDbFactory, MongoTemplate using JavaConfig also learn how to define MongoRepository to create Query methods. In this example, I will demonstrate MongoDB CRUD operation.

tags spring

Spring 4 Eclipse project set up

Spring 4 MongoDB Repository 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.

JavaConfig use the @EnableMongoRepositories annotation. This annotation helps to configure and activate MongoDB repositories. If no base package is configured then it will scan the package of the annotated configuration class.

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 MongoTemplate and MongoDbFactory 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")
@EnableMongoRepositories({ "com.technicalkeeda.repositories" })
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 Cars identified by brand name.
  7. Returns Car identified by model.
  8. 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 > findByBrand(String brand);

    public Car findByModel(String model);

    public List < Car > findAll();
}

CarServiceImpl

Mark CarServiceImpl class as "carService" using @Service annotation. Use @Autowired annotation to autowire CarRepository 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.repositories.CarRepository;

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

    @Autowired
    CarRepository carRepo;

    @Override
    public void create(Car car) {
        Car c = carRepo.insert(car);
        System.out.println("Created:- " + c);
    }

    @Override
    public void update(Car car) {
        Car c = carRepo.save(car);
        System.out.println("Updated:- " + c);

    }

    @Override
    public void delete(Car car) {
        carRepo.delete(car);
        System.out.println("Deleted:- " + car.getId());
    }

    @Override
    public List < Car > findAll() {
        return carRepo.findAll();
    }

    @Override
    public List < Car > findByBrand(String brand) {
        return carRepo.findByBrand(brand);
    }

    @Override
    public Car findByModel(String model) {
        return carRepo.findByModel(model);
    }

    @Override
    public Car find(Car car) {
        return carRepo.findOne(car.getId());
    }

    @Override
    public void deleteAll() {
        carRepo.deleteAll();
    }
}

Define MongoRepository

CarRepository interface is annotated with @Repository annotation, which extends with MongoRepository interface.

Creating Query Methods using @Query annotation. Here we can defined two methods findByModel() and findByBrand(). It is used to invoke database query by annotating the query method.

package com.technicalkeeda.repositories;

import java.util.List;

import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.data.mongodb.repository.Query;
import org.springframework.stereotype.Repository;

import com.technicalkeeda.bean.Car;

@Repository
public interface CarRepository extends MongoRepository < Car, String > {
    @Query("{ 'model' : ?0 }")
    Car findByModel(String model);

    @Query(value = "{ 'brand' : ?0}")
    List < Car > findByBrand(String brand);
}

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("\nFind One:- " + carService.find(swift));

        System.out.println("\nFind 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("\nFind By Brand = 'Volkswagen'");
        cars = carService.findByBrand("Volkswagen");
        for (Car car: cars) {
            System.out.println(car);
        }

        System.out.println("\nFind By Model = 'Ertiga'");
        System.out.println(carService.findByModel("Ertiga"));

        System.out.println("\nFind All!!");

        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.
Created:- Id:- 58609bc6290553a55deab24a, Brand:- Volkswagen, Model:- Polo
Created:- Id:- 58609bc6290553a55deab24b, Brand:- Volkswagen, Model:- Jetta
Created:- Id:- 58609bc6290553a55deab24c, Brand:- Maruti Suzuki, Model:- Swift
Created:- Id:- 58609bc6290553a55deab24d, Brand:- Maruti Suzuki, Model:- Ertiga
Created:- Id:- 58609bc6290553a55deab24e, Brand:- Hyundai, Model:- i10
Created:- Id:- 58609bc6290553a55deab24f, Brand:- Hyundai, Model:- i20

Find One:- Id:- 58609bc6290553a55deab24c, Brand:- Maruti Suzuki, Model:- Swift

Find All!!
Id:- 58609bc6290553a55deab24a, Brand:- Volkswagen, Model:- Polo
Id:- 58609bc6290553a55deab24b, Brand:- Volkswagen, Model:- Jetta
Id:- 58609bc6290553a55deab24c, Brand:- Maruti Suzuki, Model:- Swift
Id:- 58609bc6290553a55deab24d, Brand:- Maruti Suzuki, Model:- Ertiga
Id:- 58609bc6290553a55deab24e, Brand:- Hyundai, Model:- i10
Id:- 58609bc6290553a55deab24f, Brand:- Hyundai, Model:- i20

Deleted:- 58609bc6290553a55deab24c

Updated:- Id:- 58609bc6290553a55deab24e, Brand:- Hyundai, Model:- i10 Nxt

Find By Brand = 'Volkswagen'
Id:- 58609bc6290553a55deab24a, Brand:- Volkswagen, Model:- Polo
Id:- 58609bc6290553a55deab24b, Brand:- Volkswagen, Model:- Jetta

Find By Model = 'Ertiga'
Id:- 58609bc6290553a55deab24d, Brand:- Maruti Suzuki, Model:- Ertiga

Find All!!
Id:- 58609bc6290553a55deab24a, Brand:- Volkswagen, Model:- Polo
Id:- 58609bc6290553a55deab24b, Brand:- Volkswagen, Model:- Jetta
Id:- 58609bc6290553a55deab24d, Brand:- Maruti Suzuki, Model:- Ertiga
Id:- 58609bc6290553a55deab24e, Brand:- Hyundai, Model:- i10 Nxt
Id:- 58609bc6290553a55deab24f, 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("58609bc6290553a55deab24a"),
        "_class" : "com.technicalkeeda.bean.Car",
        "brand" : "Volkswagen",
        "model" : "Polo"
}
{
        "_id" : ObjectId("58609bc6290553a55deab24b"),
        "_class" : "com.technicalkeeda.bean.Car",
        "brand" : "Volkswagen",
        "model" : "Jetta"
}
{
        "_id" : ObjectId("58609bc6290553a55deab24d"),
        "_class" : "com.technicalkeeda.bean.Car",
        "brand" : "Maruti Suzuki",
        "model" : "Ertiga"
}
{
        "_id" : ObjectId("58609bc6290553a55deab24e"),
        "_class" : "com.technicalkeeda.bean.Car",
        "brand" : "Hyundai",
        "model" : "i10 Nxt"
}
{
        "_id" : ObjectId("58609bc6290553a55deab24f"),
        "_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