MongoDB-6:整合MongoBD到SpringBoot
阿新 • • 發佈:2019-01-09
一、準備工作
1.插入資料
> show dbs
admin 0.000GB
config 0.000GB
local 0.000GB
shop 0.000GB
> use shop
switched to db shop
> db.user.insert({name:'zs',age:25},{name:'ls',age:28})
WriteResult({ "nInserted" : 1 })
二、整合
1.引入依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
2.設定配置檔案
spring: mvc: view: prefix: WEB-INF/pages/ suffix: .jsp data: mongodb: host: 127.0.0.1 port: 27017 database: shop
3.建立實體:注意@Document(collection = "user"),collection指的是表名
package com.cfl.mongodb.model; import org.springframework.boot.autoconfigure.domain.EntityScan; import org.springframework.data.mongodb.core.mapping.Document; @EntityScan @Document(collection = "user") public class User { private String name; private Integer age; public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } @Override public String toString() { return "User [name=" + name + ", age=" + age + "]"; } }
4.建立Controller測試
package com.cfl.mongodb.controller;
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.ResponseBody;
import com.cfl.mongodb.model.User;
@Controller
@RequestMapping("/")
public class UserController {
@Autowired
private MongoTemplate mongoTemplate;
@RequestMapping("home")
public Object home() {
return "home";
}
@RequestMapping("findByName")
@ResponseBody
public Object findByName(String name) {
String dbName = mongoTemplate.getDb().getName();
System.out.println("資料庫名為:"+dbName);
Criteria criteria = new Criteria();
criteria.and("name").is(name);
Query query = new Query();
query.addCriteria(criteria);
User user = mongoTemplate.findOne(query, User.class);
if(user != null) {
return "home";
}
@RequestMapping("findByName")
@ResponseBody
public Object findByName(String name) {
String dbName = mongoTemplate.getDb().getName();
System.out.println("資料庫名為:"+dbName);
Criteria criteria = new Criteria();
criteria.and("name").is(name);
Query query = new Query();
query.addCriteria(criteria);
User user = mongoTemplate.findOne(query, User.class);
if(user != null) {
System.out.println("user:"+user.toString());
}
return user;
}
@RequestMapping("findByAll")
@ResponseBody
public Object findByAll() {
return mongoTemplate.findAll(User.class);
}
}