1、环境约束
- win10 64位操作系统
- idea2018.1.5
- maven-3.0.5
- jdk-8u162-windows-x64
2、前提约束
- 完成springboot创建web项目 https://www.jianshu.com/p/de979f53ad80
注意,作者使用的springboot版本是2.1.8.RELEASE - 完成安装mongodb,并启动,且有数据库实例ali,ali中有一个collection名字为student
https://www.jianshu.com/p/fa845566cbe4
3、操作步骤
- 加入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>3.4.3</version>
</dependency>
- 在application.properties中加入mongodb配置
server.port=9999
spring.data.mongodb.uri=mongodb://localhost:27017
spring.data.mongodb.database=ali
- 在主启动类同级目录下创建MongoConfig.java
import com.mongodb.MongoClient;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.gridfs.GridFSBucket;
import com.mongodb.client.gridfs.GridFSBuckets;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration//相当于xml
public class MongoConfig {
@Value("${spring.data.mongodb.database}")//直接引用的是application.properties中的key
String db;
@Bean//bean
public GridFSBucket getGridFSBucket(MongoClient mongoClient){
MongoDatabase database = mongoClient.getDatabase(db);
GridFSBucket bucket = GridFSBuckets.create(database);
return bucket;
}
}
- 在主启动类同级目录下创建MongoController.java
import com.mongodb.client.gridfs.GridFSBucket;
import com.mongodb.client.gridfs.GridFSDownloadStream;
import com.mongodb.client.gridfs.model.GridFSFile;
import org.apache.commons.io.IOUtils;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.gridfs.GridFsResource;
import org.springframework.data.mongodb.gridfs.GridFsTemplate;
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 javax.annotation.Resource;
import java.io.*;
@RestController
public class MongoController {
@Autowired
GridFsTemplate gridFsTemplate;
@Autowired
GridFSBucket gridFSBucket;
@Resource
StudentDao studentDao;
@RequestMapping("/gridfs/add")
@ResponseBody
public String addFile() throws FileNotFoundException {
//要存储的文件
File file = new File("D:\\1001.html");//假设存在该文件
//定义输入流
FileInputStream inputStram = new FileInputStream(file);
//向GridFS存储文件
ObjectId objectId = gridFsTemplate.store(inputStram, "1001", "text");
//得到文件ID
String fileId = objectId.toString();
return fileId;
}
@RequestMapping("/gridfs/fetch")
@ResponseBody
public String fetch() throws IOException {
String fileId = "5e967f8c3930f45a6c2a8e85";//假设fs.files中有这样一个文件
//根据id查询文件
GridFSFile gridFSFile =
gridFsTemplate.findOne(Query.query(Criteria.where("_id").is(fileId)));
//打开下载流对象
GridFSDownloadStream gridFSDownloadStream =
gridFSBucket.openDownloadStream(gridFSFile.getObjectId());
//创建gridFsResource,用于获取流对象
GridFsResource gridFsResource = new GridFsResource(gridFSFile, gridFSDownloadStream);
//获取流中的数据
String s = IOUtils.toString(gridFsResource.getInputStream(), "UTF-8");
return "ok";
}
@RequestMapping("/gridfs/download")
@ResponseBody
public String download() throws IOException {
// 获取文件ID
String objectId = "5e4f36ec3930f41b4456a7af";
// 获取文件流,定义存放位置和名称
File file = new File("D:/1001.html");
// 创建输出流
OutputStream os = new FileOutputStream(file);
// 执行下载
gridFSBucket.downloadToStream(new ObjectId(objectId), os);
return "ok";
}
@RequestMapping("/gridfs/delete")
@ResponseBody
public String testDelFile() throws IOException {
//根据文件id删除fs.files和fs.chunks中的记录
gridFsTemplate.delete(Query.query(Criteria.where("_id").is("5b32480ed3a022164c4d2f92")));
return "ok";
}
@RequestMapping("/mongo/insert")
@ResponseBody
public String insert(Student student) {
studentDao.save(student);
return "ok";
}
@RequestMapping("/mongo/list")
@ResponseBody
public Page<Student> list() {
Pageable pageable = PageRequest.of(1, 2);
Page<Student> page = studentDao.findAll(pageable);
return page;
}
@RequestMapping("/mongo/get/{name}")
@ResponseBody
public Page<Student> getStudentsByName(@PathVariable("name") String name) {
ExampleMatcher exampleMatcher = ExampleMatcher.matching().withMatcher("name",
ExampleMatcher.GenericPropertyMatchers.contains()).withIgnorePaths("_class");
Student info = new Student();
info.setName(name);
Example<Student> example = Example.of(info, exampleMatcher);
Pageable pageable = PageRequest.of(0, 4);
Page<Student> page = studentDao.findAll(example, pageable);
return page;
}
}
- 在主启动类同级目录下创建StudentDao.java
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface StudentDao extends MongoRepository<Student,String> {
}
- 在主启动类同级目录下创建Student.java
import org.springframework.data.mongodb.core.mapping.Document;
import java.io.Serializable;
@Document(collection = "student")
public class Student implements Serializable {
private String _id;
private String name;
private String age;
public Student() {
}
public Student(String _id, String name, String age) {
this._id = _id;
this.name = name;
this.age = age;
}
public String get_id() {
return _id;
}
public void set_id(String _id) {
this._id = _id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
}
以上就是springboot中对mongodb普通数据和文件的操作。
网友评论