学了这么多基础知识,就和学mysql一样最终的目的就是学习通过代码来连接,下面就通过一个小小的案例来熟悉SpringDatamongodb

MongoDB创建文档数据

use articledb

try {  
    db.comment.insertMany([{
    "_id": "1",
    "articleid": "100001",
    "content": "我们不应该把清晨浪费在手机上,健康很重要",
    "userid": "1002",
    "nickname": "相忘于江湖",
    "createdatetime": new Date("2019-08- 05T22:08:15.522Z"),
    "likenum": NumberInt(1000),
    "state": "1"
    },
    {
        "_id": "2",
        "articleid": "100001",
        "content": "我夏天空腹喝凉开水,冬天喝温开水",
        "userid": "1005",
        "nickname": "伊人憔 悴",
        "createdatetime": new Date("2019-08-05T23:58:51.485Z"),
        "likenum": NumberInt(888),
        "state": "1"
    },
    {
        "_id": "3",
        "articleid": "100001",
        "content": "我一直喝凉开水,冬天夏天都喝。",
        "userid": "1004",
        "nickname": "杰克船 长",
        "createdatetime": new Date("2019-08-06T01:05:06.321Z"),
        "likenum": NumberInt(666),
        "state": "1"
    },
    {
        "_id": "4",
        "articleid": "100001",
        "content": "专家说不能空腹吃饭,影响健康。",
        "userid": "1003",
        "nickname": "凯 撒",
        "createdatetime": new Date("2019-08-06T08:18:35.288Z"),
        "likenum": NumberInt(2000),
        "state": "1"
    },
    {
        "_id": "5",
        "articleid": "100001",
        "content": "研究表明,刚烧开的水千万不能喝,因为烫 嘴。",
        "userid": "1003",
        "nickname": "凯撒",
        "createdatetime": new Date("2019-08- 06T11:01:02.521Z"),
        "likenum": NumberInt(3000),
        "state": "1"
    },
    {
        "_id": "6",
        "articleid": "100001",
        "content": "这是一条分页测试",
        "userid": "1004",
        "parentid":"3",
        "nickname": "凯撒",
        "createdatetime": new Date("2019-08- 06T11:01:02.521Z"),
        "likenum": NumberInt(3000),
        "state": "1"
    }
    ]);
} catch (e) { 
    print (e); 
}

db.comment.find()

【步骤一】

​ 用idea 创建一个Springboot 项目名为 ,引入所需依赖

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-mongodb</artifactId>
    </dependency>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.18.12</version>
    </dependency>
</dependencies>

【步骤二】

​ 添加application.yml 在这里配置 MongoDB的链接

spring:
  data:
    mongodb:
      database: articledb
      host: 116.62.102.168
      port: 27017
        #也可以使用uri连接
#      uri: mongodb://116.62.102.168:27019/articledb?connect=replicaSet&slaveOk=true&replicaSet=myrs

uri的解析: https://blog.hzxbk.vip/archives/mongodb%E9%AB%98%E7%BA%A7%E9%9B%86%E7%BE%A4%E5%92%8C%E5%AE%89%E5%85%A8#springdata-%E8%BF%9E%E6%8E%A5mongodb%E5%89%AF%E6%9C%AC%E9%9B%86

创建 启动类

/**
 * @ClassName MongodbMainAppliction
 * @Description TODO
 * @Author hzx456
 * @Date 2020/4/16 12:27
 * @Version 1.0
 */
@SpringBootApplication
public class MongodbMainAppliction {
     public static void main(String[] args) {
             SpringApplication.run(MongodbMainAppliction.class,args);
         }
}

启动下看看有没有报错

【步骤三】

文章评论实体类的编写

/**
 * @ClassName Comment
 * @Description TODO
 * @Author hzx456
 * @Date 2020/4/16 12:34
 * @Version 1.0
 * 把一个java类声明为mongodb的文档,可以通过collection参数指定这个类对应的文档。
 *
 *  若未加 @Document ,该 bean save 到 mongo 的 comment collection
 *  若添加 @Document ,则 save 到 comment collection
 */

@Data
@NoArgsConstructor
@AllArgsConstructor
//复合索引
@CompoundIndex( def = "{'userid': 1, 'nickname': -1}")//推荐用命令行的形式建索引
@Document(collection="comment")////可以省略,如果省略,则默认使用类名小写映射集合
public class Comment {
    //主键标识,该属性的值会自动对应mongodb的主键字段"_id",如果该属性名就叫“id”,则该注解可以省略,否则必须写
    //    @Id
    private String id;//主键
    //该属性对应mongodb的字段的名字,如果一致,则无需该注解
    @Field("content")
    private String content;//吐槽内容
    private Date publishtime;//发布日期
    //添加了一个单字段的索引
    @Indexed
    private String userid;//发布人ID
    private String nickname;//昵称
    private LocalDateTime createdatetime;//评论的日期时间
    private Integer likenum;//点赞数
    private Integer replynum;//回复数
    private String state;//状态
    private String parentid;//上级ID
    private String articleid;

    @Override
    public String toString() {
        return "Comment{" +
                "id='" + id + '\'' +
                ", content='" + content + '\'' +
                ", publishtime=" + publishtime +
                ", userid='" + userid + '\'' +
                ", nickname='" + nickname + '\'' +
                ", createdatetime=" + createdatetime +
                ", likenum=" + likenum +
                ", replynum=" + replynum +
                ", state='" + state + '\'' +
                ", parentid='" + parentid + '\'' +
                ", articleid='" + articleid + '\'' +
                '}';
    }
}

【说明】

索引可以大大提升查询效率,一般在查询字段上添加索引,索引的添加可以通过Mongo的命令来添加,也可以在Java的实体类中通过注解添 加。

单字段索引@Indexed

复合索引注解@CompoundIndex

【步骤四】

文章评论的基本增删改查

dao层

package com.hzx.dao;

import com.hzx.entity.Comment;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.mongodb.repository.MongoRepository;

/**
 * @Author hzx456
 * @Date 2020/4/16 12:47
 * @Version 1.0
 */
public interface CommentRepository extends MongoRepository<Comment,String> {
    Page<Comment> findByParentid(String parentId, Pageable page);
}

service层

package com.hzx.service;

import com.hzx.dao.CommentRepository;
import com.hzx.entity.Comment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
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.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @ClassName CommentService
 * @Description TODO
 * @Author hzx456
 * @Date 2020/4/16 12:48
 * @Version 1.0
 */
@Service
public class CommentService {

    @Autowired
    private CommentRepository commentRepository;

    @Autowired
    private MongoTemplate mongoTemplate;



    /**
     * 保存一个评论
     * @param comment
     */
    public void saveComment(Comment comment){
        //如果需要自定义主键,可以在这里指定主键;如果不指定主键,MongoDB会自动生成主键
        //设置一些默认初始值。。。
        //调用dao
        commentRepository.save(comment);
    }

    /**
     * 更新评论
     * @param comment
     */
    public void updateComment(Comment comment){
        //调用dao
        commentRepository.save(comment);
    }

    /**
     * 根据id删除评论
     * @param id
     */
    public void deleteCommentById(String id){
        //调用dao
        commentRepository.deleteById(id);
    }

    /**
     * 查询所有评论
     * @return
     */
    public List<Comment> findCommentList(){
        //调用dao
        return commentRepository.findAll();
    }

    /**
     * 根据id查询评论
     * @param id
     * @return
     */
    public Comment findCommentById(String id){
        //调用dao
        return commentRepository.findById(id).get();
    }


    public Page<Comment> findCommentListByParentid(String parentid, int page, int size) {
        return commentRepository.findByParentid(parentid, PageRequest.of(page-1,size));
    }

    public void updateCommentLikenum(String id){

        //  查询条件
        Query query = Query.query(Criteria.where("_id").is(id));
        //  更新条件
        Update update = new Update();
        update.inc("likenum");
        mongoTemplate.updateFirst(query,update,Comment.class);
    }



}

【步骤五】

junit测试

package com.hzx;

import com.hzx.entity.Comment;
import com.hzx.service.CommentService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.Page;
import org.springframework.test.context.junit4.SpringRunner;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

/**
 * @ClassName CommentServiceTest
 * @Description TODO
 * @Author hzx456
 * @Date 2020/4/16 12:55
 * @Version 1.0
 */
@RunWith(SpringRunner.class)
@SpringBootTest
public class CommentServiceTest {
    @Resource
    private CommentService commentService;
	
    @Test
    public void testFindCommentList() {
        List<Comment> commentList = commentService.findCommentList();
       commentList.forEach(System.out::println);
    }
    @Test
    public void testFindCommentById() {
        Comment commentById = commentService.findCommentById("1");
        System.out.println(commentById);
    }

    @Test
    public void testSaveComment(){
        Comment comment=new Comment();
        comment.setArticleid("100000");
        comment.setContent("测试添加的数据");
        comment.setCreatedatetime(LocalDateTime.now());
        comment.setUserid("1006");
        comment.setNickname("温柔的兴哥哥");
        comment.setState("1");
        comment.setLikenum(0);
        comment.setReplynum(0);
        commentService.saveComment(comment);
    }

    @Test
    public void testFindCommentListByParentid() {
        Page<Comment> page = commentService.findCommentListByParentid("3", 1, 2);
        System.out.println(page.getTotalElements());
        System.out.println(page.getContent());
    }

    @Test
    public void testUpdateCommentLikenum() {
        commentService.updateCommentLikenum("5e97ea223ca05e52300a93df");
    }

}

项目目录结构:

Q.E.D.

知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议

只有不断的努力才会有更大的惊喜等着你去发现!!