1,demo结构
2,mongo依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
3,yml配置
server:
servlet:
context-path: /mongodb
port: 8080
spring:
data:
mongodb:
uri: mongodb://localhost:27017/test
4,具体实现,我这里为了没有接触过的朋友理解,实现代码我都写在controller里面
package com.xt.mongodb.controller;
import com.mongodb.client.result.DeleteResult;
import com.xt.mongodb.bean.Users;
import org.apache.tomcat.jni.User;
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.data.mongodb.core.query.Update;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import java.lang.annotation.Repeatable;
import java.util.List;
/**
* mongodb 集合的crud实现
*/
@RestController
public class TestController {
@Autowired
private MongoTemplate mongoTemplate;
//查询具体代码
@RequestMapping("/get/{name}")
public List<Users> get(@PathVariable String name){
Query query=new Query(Criteria.where("name").is(name));
//mongoTemplate.findOne(query,Users.class);带条件查询一条数据,返回实体对象
//mongoTemplate.findAll(Users.class);查询所有,返回对象集合
//我这里返回所有数据数据
return mongoTemplate.findAll(Users.class);
}
//添加具体代码
@RequestMapping("/insert")
public void insert(){
Users users = new Users("00000","小明",18,"女");
mongoTemplate.save(users);
}
//更新数据具体实现
@RequestMapping("/update")
public void update(){
Users users=new Users();
users.set_id("2");
users.setName("李斯");
users.setGender("女");
Query query=new Query(Criteria.where("_id").is(users.get_id()));//先查询
Update update=new Update().set("name",users.getName()).set("gender",users.getGender());//后修改
mongoTemplate.updateFirst(query,update,users.getClass());
}
//删除数据的具体实现
@RequestMapping("/delete")
public void delete(){
//删除的实现 根据id删除 先查找后删除
String id="2";
Query query = new Query(Criteria.where("_id").is(id));//先查询
DeleteResult remove = mongoTemplate.remove(query, Users.class);//后删除
System.out.println(remove.getDeletedCount());
}
}