当前位置: 移动技术网 > IT编程>开发语言>Java > 微服务技术系列教程(46)-SpringBoot整合MongoDB(文章评论案例)

微服务技术系列教程(46)-SpringBoot整合MongoDB(文章评论案例)

2020年07月17日  | 移动技术网IT编程  | 我要评论

01 引言

本文的代码已上传至Github,有兴趣的同学可以Clone下来看看https://github.com/ylw-github/SpringBoot-Mongo-Demo.git

讲解本文前,先熟悉MongoDB中常用的几种数据类型:

数据类型 描述
Object ID 文档ID
String 字符串,最常用,必须是有效的UTF-8
Boolean 存储一个布尔值,true或false
Integer 整数可以是32位或64位,这取决于服务器
Double 存储浮点值
Arrays 数组或列表,多个值存储到一个键
Object 用于嵌入式的文档,即一个值为一个文档
Null 存储Null值
Timestamp 时间戳
Date 存储当前日期或时间的UNIX时间格式

本文主要讲解在SpringBoot下整合MongoDB,实现文章评论的“增”、“删”、“改”、“查”功能,其中文章评论MongoDB的表结构设计如下:

专栏文章评论 comment
字段名称 字段含义 字段类型 备注
_id ID ObjectId或String Mongo的主键的字段
articleid 文章ID String
content 评论内容 String
userid 评论人ID String
nickname 评论人昵称 String
createdatetime 评论的日期时间 Date
likenum 点赞数 Int32
replynum 回复数 Int32
state 状态 String 0:不可见;1:可见;
parentid 上级ID String 如果为0表示文章的顶级评论

本文目录结构如下:
l____ 01 引言
l____ 02 环境搭建
l____ 03 配置
l____ 04 编码实现
l____ 05 单元测试

02 环境搭建

① 首先在Linux下搭建MongoDB服务,可参考之前写过的一篇文章《Linux下安装MongoDB》

② 新建一个SpringBoot-Mongo-Demo的maven项目:
在这里插入图片描述

03 配置

① 添加maven依赖,如下:

<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>
    
</dependencies>

② 配置application.yml,配置内容如下:

spring:
  #数据源配置
  data:
    mongodb:
      # 主机地址
      host: 192.168.162.137
      # 数据库
      database: articledb
      # 默认端口是27017
      port: 27017
      #也可以使用uri连接
      #uri: mongodb://bobo:123456@180.76.159.126:27017,180.76.159.126:27018,180.76.159.126:27019/articledb?connect=replicaSet&slaveOk=true&replicaSet=myrs

③ 配置启动类:

@SpringBootApplication
public class ArticleApplication {

    public static void main(String[] args) {
        SpringApplication.run(ArticleApplication.class, args);
    }
}

04 编码实现

① 定义实体类Comment

/**
 * 文章评论实体类
 * 
 * ① @Document 把一个java类声明为mongodb的文档,可以通过collection参数指定这个类对应的文档。
 * 
 * 
 * 
 * description: 
 *             - Document 把一个java类声明为mongodb的文档,可以通过collection参数指定这个类对应的文档。
 *             - 格式:@Document(collection="mongodb 对应 collection 名")
 * 
 * create by: YangLinWei
 * create time: 2020/7/15 3:28 下午
 */
//若未加 @Document ,该 bean save 到 mongo 的 comment collection
//若添加 @Document ,则 save 到 comment collection
@Document(collection="comment")//可以省略,如果省略,则默认使用类名小写映射集合
//复合索引
@CompoundIndex( def = "{'userid': 1, 'nickname': -1}")
public class Comment implements Serializable {
    //主键标识,该属性的值会自动对应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;
    //getter and setter.....
}

② 定义CommentRepository数据库:

public interface CommentRepository extends MongoRepository<Comment, String> {

    Page<Comment> findByParentid(String parentid, Pageable pageable);
}

③定义Service类:

@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);
    }
}

05 单元测试

@RunWith(SpringRunner.class)
@SpringBootTest(classes = ArticleApplication.class)
public class CommentServiceTest {

    @Autowired
    private CommentService commentService;


    @Test
    public void testFindCommentList() {
        List<Comment> commentList = commentService.findCommentList();
        System.out.println(commentList);
    }

    @Test
    public void testFindCommentById() {
        Comment commentById = commentService.findCommentById("5f0eb6d74cc07a82bf818c79");
        System.out.println(commentById);
    }

    @Test
    public void testSaveComment(){
        Comment comment=new Comment();
        comment.setArticleid("100000");
        comment.setContent("测试添加的数据");
        comment.setCreatedatetime(LocalDateTime.now());
        comment.setUserid("1001");
        comment.setNickname("ylw");
        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("5f0eb6d74cc07a82bf818c79");
    }
}

测试:

  • 测试插入,运行testSaveComment方法,在数据库中可以看到有一条数据在这里插入图片描述
  • 测试查询,运行testFindCommentById方法,可以看到结果能查询出来来在这里插入图片描述
  • 测试修改,修改点赞数量,运行testUpdateCommentLikenum方法在这里插入图片描述

本文地址:https://blog.csdn.net/qq_20042935/article/details/107361343

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网