SpringBoot集成Mongodb
本文简要介绍SpringBoot集成mongodb,并实现增删改查
1. 引入依赖
spring-boot-starter-data-mongodb 提供了mongoTemplate供底层操作及mongodb驱动等
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
2.修改配置文件
application.yml
spring:
application:
name: mongoDemo
data:
mongodb:
uri: mongodb://myUser:123456@192.168.48.137:17017/article_db
uri格式:mongodb://用户名:密码@host:端口号/数据库名称
注意:
我的mongodb版本8.0.4,运行时可能会报错,有如下三种情况
情况1:
spring:
application:
name: mongoDemo
data:
mongodb:
host: 192.168.48.137
port: 17017
database: article_db
username: myUser
password: 123456
这里说授权问题,网上说不能写用户名密码
情况2:
spring:
application:
name: mongoDemo
data:
mongodb:
host: 192.168.48.137
port: 17017
database: article_db
去掉用户名密码
这里提示大概意思是没授权
情况3:
uri: mongodb://myUser:123456@192.168.48.137:17017/article_db?authSource=admin&authMechanism=SCRAM-SHA-256
uri加后缀后仍然报错
3.创建实体类
@Document指定集合名
使用collection和value都可以,注意不要写成collation
@Field 指定集合中对应的key
@Indexed 自动创建索引
@Id
private String id;
@Field("content")
private String content;
@Field("user_id")
@Indexed
private String userId;
private String nickName;
private LocalDateTime createDate;
private Integer likeNum;
private Integer replayNum;
private String state;
private String articleId;
private String parentId;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getNickName() {
return nickName;
}
public void setNickName(String nickName) {
this.nickName = nickName;
}
public LocalDateTime getCreateDate() {
return createDate;
}
public void setCreateDate(LocalDateTime createDate) {
this.createDate = createDate;
}
public Integer getLikeNum() {
return likeNum;
}
public void setLikeNum(Integer likeNum) {
this.likeNum = likeNum;
}
public Integer getReplayNum() {
return replayNum;
}
public void setReplayNum(Integer replayNum) {
this.replayNum = replayNum;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getArticleId() {
return articleId;
}
public void setArticleId(String articleId) {
this.articleId = articleId;
}
public String getParentId() {
return parentId;
}
public void setParentId(String parentId) {
this.parentId = parentId;
}
@Override
public String toString() {
return "Comment{" +
"id='" + id + '\'' +
", content='" + content + '\'' +
", userId='" + userId + '\'' +
", nickName='" + nickName + '\'' +
", createDate=" + createDate +
", likeNum=" + likeNum +
", replayNum=" + replayNum +
", state='" + state + '\'' +
", articleId='" + articleId + '\'' +
", parentId='" + parentId + '\'' +
'}';
}
4.业务类实现
接口:
package com.example.mongodemo.article.service;
import com.example.mongodemo.article.PO.Comment;
import java.util.List;
public interface IComentService {
/**
* 保存
* @param comment
*/
void saveComment(Comment comment);
/**
* 更新
* @param comment
*/
void updateComment(Comment comment);
/**
* 根据id获取对象
* @param id
* @return
*/
Comment getById(String id);
/**
* 根据id删除
* @param ids
*/
void deleteByIds(String ...ids);
/**
* 根据条件查询
* @param articleId
* @return
*/
List<Comment> queryListByArticleId(String articleId);
/**
* 根据parentid分页查询
* @param parentId 父id
* @param page 页数从0开始
* @param size 每页条数
* @return
*/
Page<Comment> findCommentByParentId(String parentId,int page,int size);
}
实现类:
@Service
public class CommentService implements IComentService{
@Autowired
private CommentRepository repository;
@Autowired
private MongoTemplate mongoTemplate;
@Override
public void saveComment(Comment comment) {
mongoTemplate.insert(comment,"comment");
}
@Override
public void updateComment(Comment comment) {
Query query = Query.query(Criteria.where("id").is(comment.getId()));
Update update = new Update()
.set("nickname",comment.getNickName())
.set("content",comment.getContent())
.set("likeNum",comment.getLikeNum())
.set("replayNum",comment.getReplayNum())
;
mongoTemplate.updateFirst(query,update,Comment.class);
}
@Override
public Comment getById(String id) {
Query query = Query.query(Criteria.where("id").is(id));
return mongoTemplate.findOne(query,Comment.class);
}
@Override
public void deleteByIds(String... ids) {
Query query = Query.query(Criteria.where("id").in(ids));
mongoTemplate.findAllAndRemove(query,"comment");
}
@Override
public List<Comment> queryListByArticleId(String articleId) {
Query query = Query.query(Criteria.where("articleId").is(articleId));
List<Comment> commentList = mongoTemplate.find(query, Comment.class, "comment");
return commentList;
}
@Override
public Page<Comment> findCommentByParentId(String parentId, int page, int size) {
return repository.findByParentId(parentId, PageRequest.of(page,size));
}
}
持久层:
public interface CommentRepository extends MongoRepository<Comment,String > {
Page<Comment> findByParentId(String parentId, Pageable pageable);
}
5.测试
@Test
public void saveTest(){
Comment comment = new Comment();
comment.setId("1");
comment.setContent("12344334");
comment.setUserId("0001");
comment.setArticleId("0001");
comment.setNickName("张三");
comment.setLikeNum(100);
comment.setReplayNum(20);
comment.setState("1");
comment.setCreateDate(LocalDateTime.now());
commentService.saveComment(comment);
}
@Test
public void getByIdTest(){
System.out.println(commentService.getById("1"));
List<Comment> comments=mongoTemplate.findAll(Comment.class,"comment");
for(Comment comment:comments){
System.out.println(comment);
}
}
数据库: