SpringBoot.1 - MongoDB整合

目录

本文将介绍在SpringBoot中使用MongoDB的流程

引入依赖

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

配置

application.yml

spring: 
  data:
    mongodb:
      host: 192.168.52.128 # mongodb 地址
      database: covid      # 数据库名

Pojo配置

@Document(collection = "crawler_record")
public class CrawlerRecord implements Serializable {
    @Id
    private String _id;
    private String content;
    private Date updateTime;

    public String get_id() {
        return _id;
    }

    public void set_id(String _id) {
        this._id = _id;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public Date getUpdateTime() {
        return updateTime;
    }

    public void setUpdateTime(Date updateTime) {
        this.updateTime = updateTime;
    }
}

数据层

public interface CrawlerRecordRepository extends MongoRepository<CrawlerRecord, String> {
}

调用

此时就可以在service中注入服务调用

@Autowired
private CrawlerRecordRepository crawlerRecordRepository;

public void test(){
        CrawlerRecord crawlerRecord = new CrawlerRecord();
        crawlerRecord.setContent(result);

        crawlerRecord.setUpdateTime(DateUtil.parserYMDHMS(DateUtil.formatYMDHMS(new Date())));
        crawlerRecordRepository.insert(crawlerRecord);
        System.out.println(crawlerRecordRepository.findAll().size());
}

打赏一个呗

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码支持
扫码打赏,你说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦