Spring Boot集成mongodb数据库

一.认识mongodb
MongoDB是一个介于关系数据库和非关系数据库之间的产品,是非关系数据库当中功能最丰富,最像关系数据库的。它支持的数据结构非常松散,是类似json的bson格式,因此可以存储比较复杂的数据类型。Mongo最大的特点是它支持的查询语言非常强大,其语法有点类似于面向对象的查询语言,几乎可以实现类似关系数据库单表查询的绝大部分功能,而且还支持对数据建立索引。
二.Spring boot项目集成mongodb
1.添加mongodb依赖

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

2.配置mongodb的连接

spring:
    data:
            mongodb:
                #uri: mongodb://localhost:27017/data_exploration
                uri: mongodb://root:[email protected]:27017/data_exploration?authSource=admin&authMechanism=SCRAM-SHA-1

解析:以上uri分别代表本地配置和远程连接
3.操作数据库
(1)保存

@Repository
public class ExplorationJobDao {

    @Autowired
    MongoTemplate mongoTemplate;

    public void save(ExplorationJob explorationJob) {
        mongoTemplate.save(explorationJob);
    }
}

(2)根据ID修改一条数据(其原理先符合ID的数据,然后删除查询结果的第一条)

public void updateExecutionStatusById(int executionStatus, String jobId) {
            Query query = new Query(Criteria.where("jobId").is(jobId));
            Update update = new Update().set("executionStatus", executionStatus);
            mongoTemplate.updateFirst(query, update, ExplorationJob.class);
    }

(3)根据条修改多条数据(查询符合ID的所有数据,然后将所有数据修改)

public void update(BusinessExploration businessExploration) {
        Query query = new Query(Criteria.where("_id").is(businessExploration.getId()));
        Update update = new Update().set("sourceUnit", businessExploration.getSourceUnit())
                .set("appSystem", businessExploration.getAppSystem())
                .set("businessImplication", businessExploration.getBusinessImplication())
                .set("safetyRequire", businessExploration.getSafetyRequire());
        mongoTemplate.updateMulti(query, update, TableExploration.class);
    }

(4)删除(根据ID删除)

public void delExplorationJobById(String jobId) {
         Query query=new Query(Criteria.where("jobId").is(jobId));
         mongoTemplate.remove(query,ExplorationJob.class);
    }

(5)根据条件查询(根据ID查询)

public ExplorationJob getExplorationJobByJobId(String jobId) {
        Query query = new Query(Criteria.where("jobId").is(jobId));
        ExplorationJob explorationJob = mongoTemplate.findOne(query, ExplorationJob.class);
        return explorationJob;
    }

(6)查询所有


mongoTemplate.findAll(TableExploration.class);

(7)多条件动态查询

public List<ExplorationJob> getExplorationByCondition(ExplorationJob explorationJob) {
        Query query = new Query();
        if (explorationJob.getJobName() != null) {
             Pattern pattern = Pattern.compile("^.*" + explorationJob.getJobName() + ".*$", Pattern.CASE_INSENSITIVE);
             query.addCriteria(Criteria.where("jobName").regex(pattern));
        }
        if (explorationJob.getDsType() != null) {
            query.addCriteria(Criteria.where("dsType").is(explorationJob.getDsType()));
        }
        if (explorationJob.getExecutionStatus() != null) {
             query.addCriteria(Criteria.where("executionStatus").lte(explorationJob.getExecutionStatus()));
        }
        List<ExplorationJob> explorationJobs=mongoTemplate.find(query, ExplorationJob.class);
        return explorationJobs;
    }

(8)查询最大值

public Date getMaxExplorationDate(String tableName) {
        FindIterable<Document> iterable = mongoTemplate.getCollection("tableExploration")
                .find(new BasicDBObject("tableName", tableName)).sort(new BasicDBObject("explorationDate", -1)).skip(0)
                .limit(1);
        Document doc =null;
        if (getDocuments(iterable).size()>0) {
            doc=getDocuments(iterable).get(0);
            Date date = doc.getDate("explorationDate");
            return date;
        }else {
            return null;
        }
    }

    /**
     * 工具方法
     *
     * @param iterable
     * @return
     */
    public static List<Document> getDocuments(FindIterable<Document> iterable) {
        List<Document> results = new ArrayList<Document>();
        if (null != iterable) {
            MongoCursor<Document> cursor = iterable.iterator();
            Document doc = null;
            while (cursor.hasNext()) {
                doc = cursor.next();
                results.add(doc);
            }
        }
        return results;
    }

(9)分组查询(这里还是用到了排序)

public List<TableExploration> getAllTableExplorationGroupByTableName(String jobId){
        Aggregation aggregation = Aggregation.newAggregation(
                Aggregation.match(Criteria.where("jobId").is(jobId)),
                Aggregation.sort(new Sort(Direction.DESC,"explorationDate")),
                Aggregation.group("tableName")
                .first("_id").as("tableName")
                .first("databaseType").as("databaseType")
                .first("databaseName").as("databaseName")
                .first("networkSituation").as("networkSituation")
                .first("userName").as("userName")
                .first("password").as("password")
                .first("url").as("url")
                .first("dataStorage").as("dataStorage")
                .first("dataIncrement").as("dataIncrement")
                .first("explorationDate").as("explorationDate")
                //.push("columnExplorations").as("columnExplorations")
                .first("jobId").as("jobId")
                );
        AggregationResults<TableExploration> aggregationResults= mongoTemplate.aggregate(aggregation, "tableExploration", TableExploration.class);
        List<TableExploration> tableExplorations=aggregationResults.getMappedResults();
        return tableExplorations;
                                                                                                                                                                                                【常用操作总结完毕】

原文地址:https://blog.51cto.com/13501268/2448688

时间: 2024-08-28 18:36:41

Spring Boot集成mongodb数据库的相关文章

Spring Boot集成Flyway实现数据库版本控制?

今天给大家介绍一款比较好用的数据库版本控制工具Flyway.在通过Spring Boot构建微服务的过程中,一般情况下在拆分微服务的同时,也会按照系统功能的边界对其依存的数据库进行拆分.在这种情况下,微服务的数据库版本管理对于研发工程管理来说,就会是一个比较棘手的问题. 在正常的代码管理流程中,从产品研发研发的过程看,一般会经历功能开发.研发测试.集成测试.预发布测试.上线等多个环节.而对于同一个产品功能,可能还会涉及对多个微服务代码及数据库结构的改动. 而这些改动需要我们在以上流程中每发布一个

170711、spring boot 集成shiro

这篇文章我们来学习如何使用Spring Boot集成Apache Shiro.安全应该是互联网公司的一道生命线,几乎任何的公司都会涉及到这方面的需求.在Java领域一般有Spring Security.Apache Shiro等安全框架,但是由于Spring Security过于庞大和复杂,大多数公司会选择Apache Shiro来使用,这篇文章会先介绍一下Apache Shiro,在结合Spring Boot给出使用案例. Apache Shiro What is Apache Shiro?

Quartz与Spring Boot集成使用

上次自己搭建Quartz已经是几年前的事了,这次项目中需要定时任务,需要支持集群部署,想到比较轻量级的定时任务框架就是Quartz,于是来一波. 版本说明 通过搜索引擎很容易找到其官网,来到Document的页面,当前版本是2.2.x. 简单的搭建操作 通过Maven引入所需的包: <dependency> <groupId>org.quartz-scheduler</groupId> <artifactId>quartz</artifactId>

Kafka 入门和 Spring Boot 集成

Kafka 入门和 Spring Boot 集成 标签:博客 [TOC] 概述 kafka 是一个高性能的消息队列,也是一个分布式流处理平台(这里的流指的是数据流).由java 和 Scala 语言编写,最早由 LinkedIn 开发,并 2011年开源,现在由 Apache 开发维护. 应用场景 下面列举了一些kafka常见的应用场景. 消息队列 : Kafka 可以作为消息队列使用,可用于系统内异步解耦,流量削峰等场景. 应用监控:利用 Kafka 采集应用程序和服务器健康相关的指标,如应用

Spring Boot集成MyBatis实现通用Mapper

前言 MyBatis关于MyBatis,大部分人都很熟悉.MyBatis 是一款优秀的持久层框架,它支持定制化 SQL.存储过程以及高级映射.MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集.MyBatis 可以使用简单的 XML 或注解来配置和映射原生信息,将接口和 Java 的 POJOs(Plain Old Java Objects,普通的 Java对象)映射成数据库中的记录.不管是DDD(Domain Driven Design,领域驱动建模)还是分层架构的风

Spring Boot 集成 MyBatis(四)

Spring Boot 集成 MyBatis A.ORM框架是什么? 对象关系映射(Object Relational Mapping,简称 ORM)模式是一种为了解决面向对象与关系数据库存在的 互不匹配的现象技术.简单的说,ORM 是通过使用描述对象和数据库之间映射的元数据,将程序中的对象自 动持久化到关系数据库中. B.为什么需要ORM框架 当开发一个应用程序的时候(不使用 O/R Mapping),可能会写不少数据访问层的代码,用来从数据库保存. 删除.读取对象信息等.在 DAL 中写了很

Spring boot入门(二):Spring boot集成MySql,Mybatis和PageHelper插件

上一篇文章,写了如何搭建一个简单的Spring boot项目,本篇是接着上一篇文章写得:Spring boot入门:快速搭建Spring boot项目(一),主要是spring boot集成mybatis和pagehelper 关于mybatis和pagehelper的介绍,可以自行博客,网上很多类似的博客,这里,我直接上代码和项目搭建教程. 1.配置文件:在配置文件application.yml中配置MySql数据库连接池和Mybatis扫描包以及PageHelper分页插件 1 mybati

解决Spring Boot集成Shiro,配置类使用Autowired无法注入Bean问题

如题,最近使用spring boot集成shiro,在shiroFilter要使用数据库动态给URL赋权限的时候,发现 @Autowired 注入的bean都是null,无法注入mapper.搜了半天似乎网上都没有相关问题,也是奇怪.最后发现 /** * Shiro生命周期处理器 * * @return */ @Bean(name = "lifecycleBeanPostProcessor") public LifecycleBeanPostProcessor getLifecycle

Spring Boot(十一):Spring Boot 中 MongoDB 的使用

MongoDB 是最早热门非关系数据库的之一,使用也比较普遍,一般会用做离线数据分析来使用,放到内网的居多.由于很多公司使用了云服务,服务器默认都开放了外网地址,导致前一阵子大批 MongoDB 因配置漏洞被攻击,数据被删,引起了人们的注意,同时也说明了很多公司生产中大量使用 Mongodb. MongoDB 简介 MongoDB(来自于英文单词“Humongous”,中文含义为“庞大”)是可以应用于各种规模的企业.各个行业以及各类应用程序的开源数据库.基于分布式文件存储的数据库.由C++语言编