将MongoDB集成到您的Spring项目

本文展示了如何通过注释配置将MongoDB集成到您的spring项目中。

我们将从Gradle配置开始。

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'
}

我们将使用spring注释继续进行MongoDB配置。

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;
    }

}

接下来,我们将定义模型。 我们将创建位置模型,其中将包含纬度经度。

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;
    }
}

然后我们将创建我们的存储库

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> {
}

然后我们将定义我们的控制器

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;
    }

}

最后但并非最不重要的是我们的Application类

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);
    }

}

为了跑就跑

gradle bootRun

翻译自: https://www.javacodegeeks.com/2015/11/integrate-mongodb-to-your-spring-project.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值