简介
只要被springboot封装过的数据源,就意味着用法简单,具体有多简单呢?一般就是添加个引用,加个注解就集成进来了,剩下的就是功能扩展了。
为了文档好看先加简介
mongdb适用范围
MongoDB 的适合对大量或者无固定格式的数据进行存储,比如:日志、缓存等。对事物支持较弱,不适用复杂的多文档(多表)的级联查询
1.Springboot项目中添加引用
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
2、在application.yml中添加需要连接的数据库连接
在springboot中,你不需要手动去维护jdbc那套东西,已经给你封装好了,就是这么简单。
spring:
data:
mongodb:
uri: mongodb://localhost:27017/test
3、普通用法
import cn.rabbitmq.entity.Student;
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.Component;
@Component
public class UserDao{
@Autowired
private MongoTemplate mongoTemplate;
public void saveUser(Student stu) {
mongoTemplate.save(stu);
}
public Student findByUserName(String StudentName) {
Query query = new Query(Criteria.where("name").is(StudentName));
return mongoTemplate.findOne(query, Student.class);
}
}
4、骚包用法
4.1 定义文档与数据库映射实体类
@Document 这个注解就和数据库关联上了,在保存时会自动创建文档仓库
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
@Document
public class UserFileDocument {
@Id
private String id;
private String username;
private String fileId;
private String fileName;
private String path;
private boolean personal;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getFileId() {
return fileId;
}
public void setFileId(String fileId) {
this.fileId = fileId;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public boolean isPersonal() {
return personal;
}
public void setPersonal(boolean personal) {
this.personal = personal;
}
public void setPath(String path) {
this.path = path;
}
public String getPath() {
return path;
}
}
4.2 定义dao
和jpa类似,直接findby**,会自动匹配去数据库中找相关信息。该接口也不需要加注解之类的,直接用
import cn.mongoManager.entity.UserFileDocument;
import org.springframework.data.mongodb.repository.MongoRepository;
import java.util.List;
public interface UserFileDocumentDao extends MongoRepository<UserFileDocument, String> {
List<UserFileDocument> findAllByUsernameAndPersonal(String username, Boolean personal);
List<UserFileDocument> findAllByPersonal(Boolean personal);
UserFileDocument findByFileNameAndPath(String fileName, String path);
boolean existsByPath(String path);
UserFileDocument findByPath(String path);
}