Spring使用mongoDB步骤

1. 在Linux系统使用docker安装mongoDB

1.1. 安装

在docker运行的情况下,执行下述命令。

docker run \
-itd \
--name mongoDB \
-v mongoDB_db:/data/db \
-p 27017:27017 \
mongo:4.4 \
--auth

执行docker ps后,出现下列行,即表示mongoDB安装成功。(注意自行打开服务器防火墙和安全组)
在这里插入图片描述

1.2. 创建用户

登录mongo容器,并进入到【admin】数据库

 docker exec -it mongo mongo admin

创建一个用户,mongo 默认没有用户

db.createUser({ user:'root',pwd:'123456',roles:[ { role:'userAdminAnyDatabase', db: 'admin'},'readWriteAnyDatabase']});

【user: 'root’ 】:设置用户名为root
【pwd: ‘123456’】:设置密码为123456
【role: ‘userAdminAnyDatabase’】:只在admin数据库中可用,赋予用户所有数据库的userAdmin权限
【db:‘admin’】:可操作的数据库
【 ‘readWriteAnyDatabase’】:赋予用户读写权限

dbAdmin:允许用户在指定数据库中执行管理函数,如索引创建、删除,查看统计或访问system.profile

1.3. 连接、测试

1.3.1. 使用docker连接mongo数据库(这里 admin不能换成其他数据库)

docker exec -it mongoDB mongo admin -u "root" -p "123456"

或者

docker exec -it mongoDB mongo admin

进入mongoDB后再输入:

db.auth('root', '123456')

1.3.2. 测试数据库,插入一条语句

 db.user.insert({"name":"zhangsan","age":18})

1.3.3. 测试数据库,查询刚才插入的语句

 db.user.find()

在这里插入图片描述

2. Mongodb Compass-图形化界面客户端

2.1. 下载

https://www.mongodb.com/try/download/compass
在这里插入图片描述
安装过程:
MongoDB Compass的安装及使用图文说明(非常详细)

2.2. 使用

在这里插入图片描述

这里也可以看见我们刚才插入的数据。
在这里插入图片描述

3. Spring整合mongoDB

3.1. 创建工程

在这里插入图片描述

3.2. 测试项目目录结构

在这里插入图片描述

3.3. 引入依赖以及配置

pom.xml

	<parent>
	        <groupId>org.springframework.boot</groupId>
	        <artifactId>spring-boot-starter-parent</artifactId>
	        <version>2.3.9.RELEASE</version>
	        <relativePath/> <!-- lookup parent from repository -->
	</parent>
	
	<dependencies>
<!--        测试-->
		<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
<!--        mongodb-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-mongodb</artifactId>
        </dependency>
<!--        lombok-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.20</version>
            <!--            <optional>true</optional>-->
        </dependency>
    </dependencies>

application.yml

spring: #数据源配置
  data:
    mongodb: # 主机地址
      uri: mongodb://root:123456@IP:27017/articledb?authSource=admin&authMechanism=SCRAM-SHA-1

3.4. 业务代码

CommentRepository

import cn.ljwwd_cst.entity.Comment;
import org.springframework.data.mongodb.repository.MongoRepository;

//评论的持久层接口
public interface CommentRepository extends MongoRepository<Comment,String> {

}

Comment

import lombok.Data;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.index.Indexed;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.core.mapping.Field;
import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.Date;
/**
 * 文章评论实体类 
 */
//把一个java类声明为mongodb的文档,可以通过collection参数指定这个类对应的文档。
// @Document(collection="mongodb 对应 collection 名")
// 若未加 @Document ,该 bean save 到 mongo 的 comment collection
// 若添加 @Document ,则 save 到 comment collection
@Document(collection="comment")// 可以省略,如果省略,则默认使用类名小写映射集合
// 复合索引   相当于mysql中的覆盖索引
// @CompoundIndex( def = "{'userid': 1, 'nickname': -1}")
@Data
public class Comment implements Serializable {
    //主键标识,该属性的值会自动对应mongodb的主键字段"_id",如果该属性名就叫“id”,则该注解可以省略,否则必须写
    @Id
    private String id;//主键
    // 该属性对应mongodb的字段的名字,如果一致,则无需该注解
    @Field("content")
    private String content;//吐槽内容
    private Date publishtime;//发布日期
    // 添加了一个单字段的索引  userid
    @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;//文章id
}

CommentServiceImpl

import cn.ljwwd_cst.dao.CommentRepository;
import cn.ljwwd_cst.entity.Comment;
import cn.ljwwd_cst.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class CommentServiceImpl implements CommentService {
    //注入dao
    @Autowired
    private CommentRepository commentRepository;

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

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

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

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

    /***
     * 根据id查询评论
     * @param id  评论id
     * @return  Comment
     */
    @Override
    public Comment findCommentById(String id){
        //调用dao
        final Optional<Comment> byId = commentRepository.findById(id);
        if (byId.isEmpty()){
            return new Comment();
        }
        return byId.get();
    }
}

CommentService

import cn.ljwwd_cst.entity.Comment;
import java.util.List;

public interface CommentService {

    /**
     * 保存一个评论
     * @param comment 评论对象
     */
    public void saveComment(Comment comment);

    /**
     * 更新评论
     * @param comment 评论对象
     */
    public void updateComment(Comment comment);

    /**
     * 根据id删除评论
     * @param id 评论id
     */
    public void deleteCommentById(String id);

    /**
     * 查询所有评论
     * @return List<Comment>
     */
    public List<Comment> findCommentList();

    /***
     * 根据id查询评论
     * @param id  评论id
     * @return  Comment
     */
    public Comment findCommentById(String id);
}

Main

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Main {
    public static void main(String[] args) {
        SpringApplication.run(Main.class, args);
    }
}

CommentServiceTests

import cn.ljwwd_cst.Main;
import cn.ljwwd_cst.entity.Comment;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.time.LocalDateTime;

//测试评论的业务层
//SpringBoot的Junit集成测试
@RunWith(SpringRunner.class)
//SpringBoot的测试环境初始化,参数:启动类
@SpringBootTest(classes = Main.class)
public class CommentServiceTests {
    //注入Service
    @Autowired
    private CommentService commentService;

    final Comment comment = new Comment();

    /**
     * 测试
     * 保存一个评论
     */
    @Test
    public void testSaveComment(){
        comment.setArticleid("100000");
        comment.setContent("测试添加的数据");
        comment.setCreatedatetime(LocalDateTime.now());
        comment.setUserid("1001");
        comment.setNickname("test");
        comment.setState("1");
        comment.setLikenum(0);
        comment.setReplynum(0);
        System.out.println(comment.getId());
        commentService.saveComment(comment);
        System.out.println(comment.getId());
    }

    /**
     * 测试
     * 更新评论
     */
    @Test
    public void updateComment(){
        comment.setUserid("1000");
        commentService.updateComment(comment);
    }

    /**
     * 根据id删除评论
     */
    @Test
    public void deleteCommentById(){
        commentService.deleteCommentById("63f8e4506edd972c92b7f7dd");
    }

    /**
     * 查询所有评论
     */
    @Test
    public void findCommentList(){
        System.out.println(commentService.findCommentList());
    }

    /***
     * 根据id查询评论
     */
    @Test
    public void findCommentById(){
        final Comment commentById = commentService.findCommentById("63f8e4506edd972c92b7f7dd");
        System.out.println(commentById);
    }
}

测试成功如下。(注意测试代码需自行修改)
在这里插入图片描述

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值