-
引入依赖
在pom.xml
中引入所需的依赖.
<!--mongodb-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
-
添加MongoDB配置
在application.properties
文件中添加如下信息:
###mongdb相关配置
##host地址
spring.data.mongodb.host=localhost
##默认数据库端口27017
spring.data.mongodb.password=27017
##连接数据库名test
spring.data.mongodb.database=test
-
连接MongoDB
首先创建用户附件类UserAttachmentRel
package com.example.test.entity;
import org.springframework.data.annotation.Id;
/**
* 描述:用户头像关联表
* @Author zhangrui
* @Date 2019/10/31 14:17
*/
public class UserAttachmentRel {
@Id
private String id;
private String userId;
private String fileName;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
}
然后开发UserAttachmentRelRepository
类,该类继承自MongoRepository
类.
public interface UserAttachmentRelRepository extends MongoRepository<UserAttachmentRel,String> {
}
然后开发服务层接口UserAttachmentRelService
/**
* 描述:用户附件服务层
* @Author zhangrui
* @Date 2019/10/31 14:21
*/
public interface UserAttachmentRelService {
UserAttachmentRel save(UserAttachmentRel userAttachmentRel);
}
接下来实现对应的实现类UserAttachmentRelServiceImpl
/**
* 描述:用户附件实现层
* @Author zhangrui
* @Date 2019/10/31 14:22
*/
@Service
public class UserAttachmentRelServiceImpl implements UserAttachmentRelService {
@Resource
private UserAttachmentRelRepository userAttachmentRelRepository;
@Override
public UserAttachmentRel save(UserAttachmentRel userAttachmentRel) {
return userAttachmentRelRepository.save(userAttachmentRel);
}
}
-
测试
在测试类TestApplicationTests
中进行测试,将数据存储到MongoDB中
@Resource
private UserAttachmentRelService userAttachmentRelService;
@Test
public void testMongoDB(){
UserAttachmentRel userAttachmentRel = new UserAttachmentRel();
userAttachmentRel.setId("1");
userAttachmentRel.setUserId("1");
userAttachmentRel.setFileName("个人简历.doc");
userAttachmentRelService.save(userAttachmentRel);
System.out.println("保存成功");
}
打开MongoDB数据库,查看数据
至此,SpringBoot集成MongoDB成功.