springboot2.0整合mongoDB進行增刪改查和聚合,分頁

pom

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.1.3.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.xyy</groupId>
	<artifactId>cache</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>cache</name>
	<description>Demo project for Spring Boot</description>
    <packaging>jar</packaging>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
		<thymeleaf-version>3.0.0.RELEASE</thymeleaf-version>
		<thymeleaf-layout-dialect.version>2.0.0</thymeleaf-layout-dialect.version>
		<java.version>1.8</java.version>
		<elasticsearch.version>6.4.0</elasticsearch.version>
		<spring.data.elasticsearch.version>3.1.0.RELEASE</spring.data.elasticsearch.version>
	</properties>

	<dependencies>
		<!--web-->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-tomcat</artifactId>
		</dependency>
		<!--ceshi-->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
		<!--自動提示-->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-configuration-processor</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-mongodb</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-logging</artifactId>
		</dependency>
		
	</dependencies>
	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>
</project>

application.yml

spring
	mongodb:
    uri: mongodb://root:root@127.0.0.1:27017/my_test

Emp

package com.xyy.cache.bean.mongojpa;

import org.springframework.data.mongodb.core.mapping.Document;

@Document(collection = "emp")
public class Emps {


    private int empno;
    private String ename;
    private String job;
    private int mgr;
    private String hiredate;
    private int sal;
    private int depno;

    public int getEmpno() {
        return empno;
    }

    public void setEmpno(int empno) {
        this.empno = empno;
    }

    public String getEname() {
        return ename;
    }

    public void setEname(String ename) {
        this.ename = ename;
    }

    public String getJob() {
        return job;
    }

    public void setJob(String job) {
        this.job = job;
    }

    public int getMgr() {
        return mgr;
    }

    public void setMgr(int mgr) {
        this.mgr = mgr;
    }

    public String getHiredate() {
        return hiredate;
    }

    public void setHiredate(String hiredate) {
        this.hiredate = hiredate;
    }

    public int getSal() {
        return sal;
    }

    public void setSal(int sal) {
        this.sal = sal;
    }

    public int getDepno() {
        return depno;
    }

    public void setDepno(int depno) {
        this.depno = depno;
    }

    @Override
    public String toString() {
        return "Emps{" +
                "empno=" + empno +
                ", ename='" + ename + '\'' +
                ", job='" + job + '\'' +
                ", mgr=" + mgr +
                ", hiredate='" + hiredate + '\'' +
                ", sal=" + sal +
                ", depno=" + depno +
                '}';
    }
}

controller

package com.xyy.cache.controller;

import com.alibaba.fastjson.JSONObject;
import com.mongodb.BasicDBObject;
import com.xyy.cache.bean.mongojpa.Emps;
import com.xyy.cache.bean.mongojpa.MongoEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.context.annotation.Condition;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.repository.support.PageableExecutionUtils;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

@RestController
public class MongoController {
    @Autowired
    MongoTemplate mongoTemplate;

    /**
     * 向mongoDB裏插入數據
     * @param model
     * @return
     */
    @GetMapping("/add")
    public String add1(Model model){
        // Failed to convert value of type 'java.lang.String' to required type 'org.bson.types.ObjectId
        MongoEntity d =new MongoEntity();
        d.setBy("徐國亮");
        d.setDescription("zuolianxi");
        d.setLikes(500);
        d.setTags("hellowolrd");
        d.setTitle("shanchushuju");
        d.setUrl("www.baidu.com");
        model.addAttribute("mongoEntity",d);
        mongoTemplate.save(d);
        return "success";
    }

    /**
     * 查詢mongoDB是否有MongoEntity的數據
     * @param model
     * @return
     */
    @GetMapping("/list")
    @Cacheable(cacheNames = "mongo")
    public List add(Model model){
        List<MongoEntity> departmentList = mongoTemplate.findAll(MongoEntity.class);
        for (MongoEntity department :departmentList) {
            System.out.println(department);
        }
        model.addAttribute("departmentList",departmentList);
        return departmentList ;
    }

    @ResponseBody
    @GetMapping("/getUser")
    public List findAll(){
        List<Emps> departmentList = mongoTemplate.findAll(Emps.class);
        if(CollectionUtils.isEmpty(departmentList)){
            List list=new ArrayList();
            list.add("沒有查詢到數據");
            return list;
        }else {
            return departmentList ;
        }
    }

    //一. 常用查詢1. 查詢一條數據:(多用於保存時判斷db中是否已有當前數據,這裏 is  精確匹配,模糊匹配 使用 regex...)
    @ResponseBody
    @GetMapping("/findOne")
    public List findOne() {
        System.out.println("進入查詢一條數據方法");
        return mongoTemplate.find(new Query(Criteria.where("ename").is("吳用")),Emps.class);
    }

    //查詢多條數據: 屬於分級查詢,limit不指定就查所有,skip表示跳過的行數,不指定就不跳過
    //mongoTemplate.find(new Query().limit(rows).skip((page-1)*rows),Emps.class)
    //pageindex顯示的當前頁,pageSize,顯示的記錄數
    @ResponseBody
    @GetMapping("/getPagedUser")
    public PageImpl<Emps> getPagedUser(int page, int rows) {
        System.out.println("查詢多條數據: 屬於分級查詢");
        Query query=new Query();
        //每頁五個
        Pageable pageable=new PageRequest(page,rows);
        query.with(pageable);
        //按sal排序
        query.with(new Sort(Sort.Direction.DESC,"sal"));
        //查詢總數
        Long count=mongoTemplate.count(query,Emps.class,"emp");
        List<Emps> emps=mongoTemplate.find(query,Emps.class);
        return (PageImpl<Emps>)PageableExecutionUtils.getPage(emps,pageable,()->count);
    }

    //模糊查詢
    @ResponseBody
    @GetMapping("/like")
    public List like() {
        Query query = new Query(new Criteria().where("job").regex(Pattern.compile("^.*.職.*$",Pattern.CASE_INSENSITIVE)));
        return mongoTemplate.find(query,Emps.class);
    }

    //多條件查詢
    @ResponseBody
    @GetMapping("/manyCase")
    public List manyCase() {
        Query query = new Query();
        query.addCriteria(Criteria.where("depno").is(20));
        query.addCriteria(Criteria.where("sal").gte(1200));
        return mongoTemplate.find(query,Emps.class);
    }

    /*
     * project:列出所有本次查詢的字段,包括查詢條件的字段和需要搜索的字段;
     * match:搜索條件criteria
     * unwind:某一個字段是集合,將該字段分解成數組
     * group:分組的字段,以及聚合相關查詢
     *      sum:求和(同sql查詢)
     *      count:數量(同sql查詢)
     *      as:別名(同sql查詢)
     *      addToSet:將符合的字段值添加到一個集合或數組中
     * sort:排序
     * skip&limit:分頁查詢
     */
    @ResponseBody
    @GetMapping("/agreegation")
    public List agreegation() {
        //統計部門人數
        Aggregation aggregation=Aggregation.newAggregation(Aggregation.group("depno").count().as("部門人數"));
        AggregationResults results=mongoTemplate.aggregate(aggregation,"emp", BasicDBObject.class);
        return results.getMappedResults();
    }
    //or
    /*@ResponseBody
    @GetMapping("/orOperator")
    public List orOperator() {
        Query query=new Query(Criteria.where("sal").gt(1500)
        .orOperator(Criteria.where("empno")).is(7782));
        return mongoTemplate.find(query,Emps.class);
    }*/
}

數據展示
在這裏插入圖片描述

效果可以使用postMan自行演示,這裏只演示查詢所有,查詢分頁
在這裏插入圖片描述

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章