1.添加依赖:
org.springframework.boot spring-boot-starter-data-mongodb
2.实体类,注意加上 @Document(collection="test")
import org.springframework.data.mongodb.core.mapping.Document;
@Document(collection="test")
public class Test {
private int age;
public Test() {
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
3.配置文件连接mongdb
spring.data.mongodb.host=127.0.0.1
spring.data.mongodb.port=27000
spring.data.mongodb.database=test001
4controller层
import com.test.beans.Test;
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.web.bind.annotation.*;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
@RestController
@RequestMapping("/mongodbController")
public class MongodbController {
@Autowired
private MongoTemplate mongoTemplate;
/**表名==集合*/
private static final String collectionName = " test ";
/**
* 描述:新增
*/
@RequestMapping(value = "/insert", method = RequestMethod.POST)
@ResponseBody
public ResultObject insert(@ModelAttribute Test test) throws Exception {
this.mongoTemplate.insert(test);
return new ResultObject(HttpServletResponse.SC_OK);
}
/**
* 描述:删除
*/
@RequestMapping("/delete")
@ResponseBody
public ResultObject delete(@RequestParam("age") String age) throws Exception {
Query query = Query.query(Criteria.where("age").is(age));
this.mongoTemplate.remove(query, collectionName);
return new ResultObject(HttpServletResponse.SC_OK);
}
/**
* 描述:修改
*/
@RequestMapping(value = "/update", method = RequestMethod.POST)
@ResponseBody
public ResultObject update(@ModelAttribute Test test) throws Exception {
Query query = Query.query(Criteria.where("age").is(test.getAge()));
Update update = new Update();
update.set("age", test.getAge());
this.mongoTemplate.updateFirst(query, update, collectionName);
return new ResultObject(HttpServletResponse.SC_OK);
}
/**
* 描述:查询
*/
@RequestMapping("/query")
@ResponseBody
public ResultObject query() throws Exception {
Query query = Query.query(Criteria.where("age").is(1));
List
return new ResultObject(HttpServletResponse.SC_OK, tests);
}
}