springboot整合MongoDB
前提:下载安装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(); } } }