springboot整合MongoDB

前提:下载安装 MongoDB,

安装完成之后,找到安装路径,点击如下文件打开界面:

 

 

一、 在 pom.xml 文件中加入如下依赖包 

1
2
3
4
5
6
<!--=================mongoDb依赖包==============-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-mongodb</artifactId>
        </dependency>
<!--===============================-->

 

二、在 application.yml 中配置 mongdb 连接

1
2
3
4
5
6
spring:
  data:
    mongodb:
      database: testMGDB
      host: localhost
      port: 27017

  

三、测试 MongoDB

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
package com.example.demo.Controller;
 
 
import com.example.demo.entity.MyTest;
import com.example.demo.servive.MyTestService;
import org.springframework.beans.factory.annotation.Autowired;
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.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
 
import java.util.List;
 
@Controller
@RequestMapping("mgDb")
public class MgDbController {
    @Autowired
    private MyTestService myTestService;
    @Autowired
    private MongoTemplate mongoTemplate;
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public void save(int id,String name) {
        try{
            List<MyTest> myTestList = myTestService.findAll();
            mongoTemplate.save(myTestList.get(0),"myTest");  //向MongoDB里面插入数据
            List<MyTest> list = mongoTemplate.findAll(MyTest.class,"myTest"); //从MongoDB查询插入数据
 
            //一般查询
            Query query = new Query();
            Criteria criteria = Criteria.where("id").is(id);  //查询条件"id"指MongoDB里面的key
            criteria.and("name").is(name);  //and条件
            query.addCriteria(criteria);
            MyTest myTest = mongoTemplate.findOne(query,MyTest.class,"myTest");
 
            System.out.println("success");
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}