Spring Boot整合MongoDB

Spring Boot整合MongoDB

引入jar

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

<!--lombok-->
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
</dependency>

配置文件

spring:
  data:
    mongodb:
      host: 114.45.252.295
      database: admin
      port: 27017
      # 也可以使用uri连接
      # uri: mongodb://localhost:27017/xxxdb
      username: root
      password: root

Comment表为例,创建实体类

@Data
@Document(collection = "comment")
// 复合索引 建议命令行
@CompoundIndex(def = "{'userId':1,'nickName':1}")
public class Comment implements Serializable {
    /**
     * 主键
     */
    @Id
    private String id;

    @Field("comment")
    private String comment;

    @Indexed
    private String userId;

    private String nickName;

    private Date createDateTime;

    private Integer likeNum;

    private Integer replyNum;

    private String state;

    private String parentId;

}

1. Dao

继承自MongoRepository<T,ID>,里面为我们生成了基本的增删改查方法。

若需要自定义方法,则需要根据MongoDB自定义方法规则进行创建。

public interface CommentRepository extends MongoRepository<Comment,String> {
    /**
     * 固定命名格式(分页)
     * @param parentId
     * @param pageable
     * @return
     */
    Page<Comment> findByParentId(String parentId, Pageable pageable);
}

2. Service

整体跟我们平常使用的MVC三层架构差不多。MongoTemplateRedisTemplate使用也很相似。

@Service
public class CommentService {

    @Autowired
    private CommentRepository commentRepository;

    @Autowired
    private MongoTemplate mongoTemplate;

    public void updateCommentLikeNum(String id){
        // 1.查询条件
        Query query = Query.query(Criteria.where("_id").is(id));
        // 2.更新条件
        Update update = new Update().inc("likeNum",1);


        mongoTemplate.updateFirst(query,update,Comment.class);
    }


    /**
     * 分页查询
     * @param parentId
     * @param page
     * @param size
     * @return
     */
    public Page<Comment> findCommentListByParentId(String parentId, int page, int size) {
        return commentRepository.findByParentId(parentId, PageRequest.of(page - 1, size));
    }

    /**
     * 增加一个评论
     *
     * @param comment
     */
    public void saveComment(Comment comment) {
        commentRepository.save(comment);
    }

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

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

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

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

3. 测试使用

@SpringBootTest
public class CommentServiceTest {

    @Autowired
    private CommentService commentService;


    @Test
    public void testSaveComment(){
        Comment comment = new Comment();
        comment.setComment("开水不能直接喝!");
        comment.setState("1");
        comment.setLikeNum(99);
        comment.setUserId("1");
        comment.setNickName("张三");
        comment.setParentId("3");
        comment.setReplyNum(null);
        comment.setCreateDateTime(new Date());

        commentService.saveComment(comment);
    }

    @Test
    public void testFindCommentList(){
        commentService.findCommentList().forEach(System.out::println);
    }

    @Test
    public void testFindCommentById(){
        System.out.println(commentService.findCommentById("643e4452a8f77121df39de72").toString());
    }

    @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 updateCommentLikeNum(){
        commentService.updateCommentLikeNum("643e4452a8f77121df39de72");
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值