springboot 集成 mongo

2018-06-08  本文已影响0人  智勇双全的小六

学习教程:

客户端默认配置

  1. ip 默认是 localhost
  2. 端口默认是 27017
  3. database默认的是test,mongodb中默认有两个数据库admin、local

引入依赖

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

快速开始

一切使用自动配置,默认使用 test 数据库;
这个套路和使用mybatis是一样的,并且比使用mybatis 简单,因为不用配置 xml 的sql 语句。

创建要存储的 BoxVideoPage 实体

public class BoxVideoPage {

    @Id
    private Long id;
    private Integer boxId;
    private String boxVideoPageUrl;
    private String boxVideoPageHtml;

    public BoxVideoPage(Long id, Integer boxId, String boxVideoPageUrl, String boxVideoPageHtml) {
        this.id = id;
        this.boxId = boxId;
        this.boxVideoPageUrl = boxVideoPageUrl;
        this.boxVideoPageHtml = boxVideoPageHtml;
    }

  // getter and setter

搞一个接口出来

public interface BoxVideoPageMapper extends MongoRepository<BoxVideoPage, Long> {
    BoxVideoPage findByBoxId(Integer boxId);
}

使用

    @RequestMapping("test/box-video")
    public String getBoxVideo(){
        boxVideoPageMapper.save(new BoxVideoPage(2L,2,"pageUrl2","html2"));
        System.out.println(boxVideoPageMapper.findByBoxId(1));
        return "";
    }

打开mongo shell,查看插入的数据

use test
db.boxVideoPage.find()

进行相关配置

不使用默认设置,进行相关配置

spring.data.mongodb.uri=mongodb://name:pass@localhost:27017/test
上一篇 下一篇

猜你喜欢

热点阅读