前提:下載安裝MongoDB,

安裝完成之后,找到安裝路徑,點擊如下文件打開界面:



一、 在pom.xml文件中加入如下依賴包
<!--=================mongoDb依賴包==============--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-mongodb</artifactId> </dependency> <!--===============================-->
二、在application.yml中配置mongdb連接
spring:
data:
mongodb:
database: testMGDB
host: localhost
port: 27017

三、測試MongoDB
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();
}
}
}
