springboot+MongoDB基本操作

使用SpringDataMongoDB:SpringData家族成员之一,使用jpa语法,非常方便的就可以操作MongoDB。

首先第一步导依赖:

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-mongodb</artifactId>
        </dependency>

2. 在application.yml中连接配置

spring:
  data:
    mongodb:
      database: 文档名
      host: ip地址

3.创建对应的实体类

4.配置一个dao操作MongoDB的类继承 MongoRepository<实体, 主键类型>

/**
 * @Description:
 * @Author: liuzian
 * @Date: Create in 23:38 2020/4/10
 */
@Repository
public interface CommentDao extends MongoRepository<Comment,String> {
    
}

5.最后在测试类中进行测试

好,简单对MongoDB的操作就记录到这里了,crud跟jpa的语法是相同的.用到再补充

在dao上写一个方法,实现某一个功能.

方法名定义必须是这样子的哦,第一次还真的是有点秀到我了........................ 

MongoDB表中表保存操作(这个感觉有点秀啊) 

     场景是 在帖子评价这个实体类中添加博客跟评价人两个属性,当保存的时候,可以把三部分的数据一起保存,好处就是查询这个评价的时候可以随便把对应的评价人信息跟博客信息一同查出来.(好像有点绕,直接操作上图===)

1.测试代码

 @Autowired
    private CommentDao commentDao;
    @Test
    public void testSave() {
        Comment comment = new Comment();
        comment.setCommentBlog("4");
        comment.setCommentContent("我是帖子的评论内容4 ");
        comment.setCommentGood(0);
        comment.setCommentUser(123);
        comment.setCreatedTime(LocalDate.now().toString());
        //保存评价人信息
        User user = new User();
        user.setUserId(123);
        user.setName("liuzian");
        //保存博客信息
        Blog blog = new Blog();
        blog.setBlogId("4");
        blog.setBlogContent("这是博客内容");
        comment.setBlog(blog);
        comment.setUser(user);
        commentDao.save(comment);
    }

保存成功了,我们查询转成json格式的看是啥样子的

{
	"blog": {
		"blogContent": "这是博客内容",
		"blogId": "4"
	},
	"commentBlog": "4",
	"commentContent": "我是帖子的评论内容4 ",
	"commentGood": 0,
	"commentUser": 123,
	"createdTime": "2020-04-11",
	"id": "5e9196908e705d0c5cf06ac7",
	"user": {
		"name": "liuzian",
		"userId": 123
	}
}

还是挺赞的

发布了15 篇原创文章 · 获赞 30 · 访问量 10万+

猜你喜欢

转载自blog.csdn.net/qq_39848608/article/details/105454433