Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Integrate MongoDB Into Your Spring Project

DZone's Guide to

Integrate MongoDB Into Your Spring Project

This article shows how to integrate MongoDB into your Spring project through annotation configuration.

· Database Zone ·
Free Resource

MariaDB TX, proven in production and driven by the community, is a complete database solution for any and every enterprise — a modern database for modern applications.

This article shows how to integrate MongoDB into your Spring project through annotation configuration.

We will begin with our Gradle configuration.

group 'com.gkatzioura.spring'
version '1.0-SNAPSHOT'


buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:1.2.7.RELEASE")
    }
}

apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'idea'
apply plugin: 'spring-boot'

jar {
    baseName = 'mdb-spring-boot'
    version =  '0.1.0'
}

repositories {
    mavenCentral()
}

sourceCompatibility = 1.8
targetCompatibility = 1.8

dependencies {


    compile("org.springframework.boot:spring-boot-starter-web")


    compile('com.googlecode.json-simple:json-simple:1.1.1')
    compile("org.springframework.boot:spring-boot-starter-actuator")
    compile("org.springframework.data:spring-data-mongodb:1.8.0.RELEASE")
    compile("ch.qos.logback:logback-classic:1.1.3")
    compile("ch.qos.logback:logback-core:1.1.3")
    compile("org.json:json:20150729")
    compile("com.google.code.gson:gson:2.4")

    compile("org.slf4j:slf4j-api:1.7.12")

    testCompile("junit:junit")
    testCompile('org.springframework.boot:spring-boot-starter-test')
}

task wrapper(type: Wrapper) {
    gradleVersion = '2.3'
}

We will proceed with the MongoDB configuration using spring annotations.

package com.gkatzioura.spring.config;

import com.mongodb.MongoClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoDbFactory;

import java.net.UnknownHostException;

/**
 * Created by oSeven3 on 21/10/2015.
 */
@Configuration
public class MongoDbConfiguration {

    public @Bean MongoDbFactory getMongoDbFactory() throws UnknownHostException {
        return new SimpleMongoDbFactory(new MongoClient("localhost",27017),"mongotest");
    }

    public @Bean(name = "mongoTemplate") MongoTemplate getMongoTemplate() throws UnknownHostException {

        MongoTemplate mongoTemplate = new MongoTemplate(getMongoDbFactory());
        return mongoTemplate;
    }

}

Next we will define our model. We shall create the Location model which will contain the latitude longitude.

package com.gkatzioura.spring.persistence.entities;

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

import java.math.BigDecimal;
import java.util.Date;
import java.util.UUID;

@Document(collection = "location")
public class Location {

    @Id
    private String id;
    private BigDecimal latitude;
    private BigDecimal longitude;
    private Date timestamp;

    public String getId() {
        return id;
    }

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

    public BigDecimal getLatitude() {
        return latitude;
    }

    public void setLatitude(BigDecimal latitude) {
        this.latitude = latitude;
    }

    public BigDecimal getLongitude() {
        return longitude;
    }

    public void setLongitude(BigDecimal longitude) {
        this.longitude = longitude;
    }

    public Date getTimestamp() {
        return timestamp;
    }

    public void setTimestamp(Date timestamp) {
        this.timestamp = timestamp;
    }
}

Then we shall create our repository:

package com.gkatzioura.spring.persistence.repositories;

import com.gkatzioura.spring.persistence.entities.Location;
import org.springframework.data.repository.CrudRepository;

import java.util.UUID;

public interface LocationRepository extends CrudRepository<Location,String> {
}

Then we shall define our controller:

package com.gkatzioura.spring.controller;

import com.gkatzioura.spring.persistence.entities.Location;
import com.gkatzioura.spring.persistence.repositories.LocationRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

import java.io.IOException;

/**
 * Created by oSeven3 on 21/10/2015.
 */

@RestController
@RequestMapping("/location")
public class LocationController {

    @Autowired
    private LocationRepository locationRepository;

    private static final Logger LOGGER = LoggerFactory.getLogger(LocationRepository.class);

    @RequestMapping(value = "/",method = RequestMethod.POST)
    @ResponseBody
    public String post(@RequestBody Location location) {

        locationRepository.save(location);

        return "OK";
    }

    @RequestMapping(value = "/",method = RequestMethod.GET)
    @ResponseBody
    public List<Location> get() {

        List<Location> locations = new ArrayList<>();
        locationRepository.findAll().forEach(l->locations.add(l));
        return locations;
    }

}

Last but not least our Application class:


package com.gkatzioura.spring;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * Created by gkatziourasemmanouil on 8/15/15.
 */
@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

}

In order to run just run:

gradle bootRun


MariaDB AX is an open source database for modern analytics: distributed, columnar and easy to use.

Topics:
mongodb ,spring

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}