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.5.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.zhaolei</groupId>
    <artifactId>mongodb-springboot</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>mongodb-springboot</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

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

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.56</version>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

application.yml配置

spring:
  data:
    mongodb:
      host: ********
      database: studentdb

pojo实体类
Student表

package com.zhaolei.mongodbspringboot.pojo;

import lombok.Data;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.DBRef;
import org.springframework.data.mongodb.core.mapping.Document;

/**
 * @author 15579
 * 2019/6/13 14:26
 * 文件说明:
 */
@Document(collection = "student")
@Data
public class Student {

    private Integer id;
    private String name;
    private String sex;
    private Integer gradeId;
//    @DBRef
//    private  Grade grade;
}

注意这里注释的grade表的对象可以写可以不写(写了的话两表联查查询出来的结果集合泛型可以是studnt实体类也可以是Map)
Grade表

package com.zhaolei.mongodbspringboot.pojo;

import lombok.Data;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;

/**
 * @author 15579
 * 2019/6/13 15:16
 * 文件说明:
 */
@Document(collection = "grade")
@Data
public class Grade {

    private  Integer id;
    private  String gradeName;
}

dao层

package com.zhaolei.mongodbspringboot.dao;

import com.mongodb.BasicDBObject;
import com.zhaolei.mongodbspringboot.pojo.Student;

import java.util.List;

/**
 * @author 15579
 * 2019/6/13 14:28
 * 文件说明:
 */
public interface StudentDao {

    //新增
    void saveStudent(Student student);

    //删除
    void removeStudent(Integer id);

    //修改
    void updateStudent(Student student);

    //根据编号查询
    Student findById(Integer id);

    //查询所有
    List<Student> findAll();

    /**
     * 两表联查
     * @return
     */
    Object findStudentAndGrade();
}

dao层实现类

package com.zhaolei.mongodbspringboot.dao.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mongodb.BasicDBObject;
import com.zhaolei.mongodbspringboot.dao.StudentDao;
import com.zhaolei.mongodbspringboot.pojo.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.*;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

import static org.springframework.data.mongodb.core.query.Criteria.*;

/**
 * @author 15579
 * 2019/6/13 14:33
 * 文件说明:
 */
@Component
public class StudentDaoImpl implements StudentDao {

    @Autowired
    private MongoTemplate mongoTemplate;

    //新增
    @Override
    public void saveStudent(Student student) {
        mongoTemplate.save(student);
    }

    //删除
    @Override
    public void removeStudent(Integer id) {
        Query query=new Query(Criteria.where("_id").is(id));
        mongoTemplate.remove(query,Student.class);
    }

    //修改
    @Override
    public void updateStudent(Student student) {
        Query query=new Query(Criteria.where("_id").is(student.getId()));
        Update update=new Update();
        update.set("name",student.getName());
        update.set("sex",student.getSex());
        update.set("gradeId",student.getGradeId());
        mongoTemplate.updateFirst(query,update,Student.class);
    }

    //根据编号查询
    @Override
    public Student findById(Integer id) {
        Query query=new Query(Criteria.where("_id").is(id));//可累加条件
        Student student = mongoTemplate.findOne(query, Student.class);
        return student;
    }

    //查询所有
    @Override
    public List<Student> findAll() {
        return mongoTemplate.findAll(Student.class);
    }

    /**
     * 两表联查
     *
     * @return
     */
    @Override
    public Object findStudentAndGrade() {
        LookupOperation lookupOperation=LookupOperation.newLookup().
                from("grade").  //关联从表名
                localField("gradeId").     //主表关联字段
                foreignField("_id").//从表关联的字段
                as("GradeAndStu");   //查询结果名
//带条件查询可以选择添加下面的条件
//       Criteria criteria=Criteria.where("studenAndgrade").not().size(0);   //只查询有结果的学生
//        Criteria qqq=Criteria.where("name").regex("文");//只查询名字中带有文的
 //       AggregationOperation match1= Aggregation.match(qqq);
//        AggregationOperation match = Aggregation.match(criteria);
//        Aggregation counts = Aggregation.newAggregation(match1,lookupOperation,match).;
       Aggregation aggregation=Aggregation.newAggregation(lookupOperation);
        List<Map> results = mongoTemplate.aggregate(aggregation,"student", Map.class).getMappedResults();
        //上面的student必须是查询的主表名
        System.out.println(JSON.toJSONString(results));
        return results;
    }
}

controller层

package com.zhaolei.mongodbspringboot.controller;

import com.zhaolei.mongodbspringboot.dao.StudentDao;
import com.zhaolei.mongodbspringboot.pojo.Student;
import jdk.nashorn.internal.ir.ReturnNode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * @author 15579
 * 2019/6/13 14:44
 * 文件说明:
 */
@RestController
public class StudentController {

    @Autowired
    private StudentDao studentDao;

    //查询所有
    @GetMapping("/students")
    public Object findAll(){
        return studentDao.findAll();
    }

    //根据编号查询
    @GetMapping("/findById")
    public Object findById(Integer id){
        return studentDao.findById(id);
    }

    //根据编号删除
    @DeleteMapping("/students/{id}")
    public  Object removeStudent(@PathVariable("id") Integer id){
        try {
            studentDao.removeStudent(id);
            return 200;
        }catch (Exception e){
            e.printStackTrace();
            return  500;
        }
    }

    //修改
    @PutMapping("/students")
    public Object updateStudent(Student student){
        studentDao.updateStudent(student);
        return student;
    }


    //新增
    @PostMapping("/students")
    public  Object saveStudent(Student student){
        studentDao.saveStudent(student);
        return  student;
    }

    //多表联查
    @GetMapping("/findStudentAndGrade")
    public Object findStudentAndGrade(){
        return studentDao.findStudentAndGrade();
    }
}

启动项目

这里其他接口我就不测试了,重点测试一下聚合查询(多表联查)的结果
使用Postman测试,查询结果如下:
在这里插入图片描述

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐