【springboot】mongoTemplate增删改查操作

目录

        • 一、代码示例
          • 1.1 pom依赖
          • 1.2 application配置
          • 1.3 controller
          • 1.4 service
        • 二、截图示例
          • 2.1 新增
          • 2.2 修改
          • 2.3 详情
          • 2.4 分页
          • 2.5 删除

一、代码示例

1.1 pom依赖


    org.springframework.boot
    spring-boot-starter-data-mongodb


1.2 application配置
spring:
  data:
    mongodb:
      uri: mongodb://127.0.0.1/learning
1.3 controller
package com.learning.mongodb.controller;

import com.learning.mongodb.entity.Page;
import com.learning.mongodb.entity.PageQuery;
import com.learning.mongodb.entity.Student;
import com.learning.mongodb.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * @Description 接口类
 */
@RequestMapping("student")
@RestController
public class StudentController {

    @Autowired
    private StudentService studentService;

    @GetMapping("/{id}")
    @ResponseBody
    public Student getById(@PathVariable String id){
        return studentService.getById(id);
    }

    @PostMapping("/save")
    @ResponseBody
    public Student save(@RequestBody Student student){
        return studentService.save(student);
    }

    @DeleteMapping("/{id}")
    public long remove(@PathVariable String id){
        return studentService.remove(id);
    }

    @PutMapping("/update")
    public Student update(@RequestBody Student student){
        return studentService.update(student);
    }

    @GetMapping("/page")
    public Page page(Student student, PageQuery query) {
        return studentService.page(student, query);
    }
}

1.4 service
package com.learning.mongodb.service.impl;

import com.learning.mongodb.entity.Page;
import com.learning.mongodb.entity.PageQuery;
import com.learning.mongodb.entity.Student;
import com.learning.mongodb.service.StudentService;
import com.mongodb.BasicDBObject;
import com.mongodb.client.result.DeleteResult;
import com.mongodb.client.result.UpdateResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
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.Service;

import java.util.*;

@Service
public class StudentServiceImpl implements StudentService {

    public static String COLLECTION_NAME = "school";

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 根据id检索
     * @param id
     * @return
     */
    @Override
    public Student getById(String id) {
        Query query = new Query(Criteria.where("id").is(id));
        Student student = mongoTemplate.findOne(query, Student.class, COLLECTION_NAME);
        return student;
    }

    @Override
    public Student save(Student student) {
        // 判断collection是否存在
        if(mongoTemplate.collectionExists(COLLECTION_NAME)){
            // 保存数据
            return mongoTemplate.insert(student, COLLECTION_NAME);
        }else{
            // 创建collection
            BasicDBObject index = new BasicDBObject();
            index.put("id", 1);
            mongoTemplate.createCollection(COLLECTION_NAME).createIndex(index);
            // 保存数据
            return mongoTemplate.insert(student, COLLECTION_NAME);
        }
    }

    @Override
    public long remove(String id) {
        Query query = Query.query(Criteria.where("_id").is(id));
        DeleteResult result = mongoTemplate.remove(query, COLLECTION_NAME);
        return result.getDeletedCount();
    }

    @Override
    public Student update(Student student) {
        Query query = new Query(Criteria.where("_id").is(student.getId()));
        Student one = mongoTemplate.findOne(query, Student.class, COLLECTION_NAME);
        if(one != null){
            Update update = new Update();
            update.set("age", student.getAge());
            update.set("name", student.getName());
            UpdateResult updateResult = mongoTemplate.updateFirst(query, update, COLLECTION_NAME);
            long modifiedCount = updateResult.getModifiedCount();
            if(modifiedCount>0){
                return student;
            }
        }
        return null;
    }

    public long updateBatch(List ids) {
        Update update = new Update();
        update.set("updateTime", new Date());
        update.set("deleted", 1);
        Query query = new Query(Criteria.where("_id").in(ids));
        UpdateResult updateResult = mongoTemplate.updateMulti(query, update, COLLECTION_NAME);
        return updateResult.getModifiedCount();
    }

    private List list(Student student) {
        Criteria criteria = new Criteria();
        if(student.getAge() != null){
            criteria.and("age").is(student.getAge());
        }
        if(student.getName() != null){
            // 模糊查询
            criteria.and("name").regex(student.getName());
        }
        Query query = new Query(criteria);
        return mongoTemplate.find(query, Student.class, COLLECTION_NAME);
    }

    @Override
    public Page page(Student student, PageQuery pageQuery) {
        // 查询总数
        long count = this.count(student);
        Page page = new Page<>();
        page.setTotal(count);
        page.setSize(pageQuery.getSize());
        page.setCurrent(pageQuery.getCurrent());
        if(count > 0){
            List dataList = this.getPage(student, pageQuery);
            page.setRecords(dataList);
        }
        return page;
    }

    private List getPage(Student student, PageQuery pageQuery) {
        Query query = getQuery(student);
        if(query != null){
            query.with(PageRequest.of(pageQuery.getCurrent() - 1, pageQuery.getSize()));
        }
        return mongoTemplate.find(query, Student.class, COLLECTION_NAME);
    }

    private Query getQuery(Student student) {
        Criteria criteria = new Criteria();
        if(student.getAge() != null){
            criteria.and("age").is(student.getAge());
        }
        if(student.getName() != null){
            // 模糊查询
            criteria.and("name").regex(student.getName());
        }
        Query query = new Query();
        query.addCriteria(criteria);
        Sort sort = Sort.by(Sort.Order.asc("id"));
        query.with(sort);
        return query;
    }

    private long count(Student student) {
        Query query = this.getQuery(student);
        return mongoTemplate.count(query, COLLECTION_NAME);
    }
    
//    private Query andOr(Student student) {
//        Criteria criteria = new Criteria();
//        criteria.and("age").is(student.getAge());
//
//        Query query = new Query();
//        List list = new ArrayList<>();
//        list.add(criteria);
//
//        Criteria keyWordCriteria = new Criteria().orOperator(
//                Criteria.where("name").regex(student.getName()),
//                Criteria.where("description").regex(student.getDescription())
//        );
//        list.add(keyWordCriteria);
//        Criteria result = new Criteria().andOperator(list);
//        query.addCriteria(result);
//        Sort sort = Sort.by(Sort.Order.asc("id"));
//        query.with(sort);
//        return query;
//    }
}

二、截图示例

2.1 新增

【springboot】mongoTemplate增删改查操作_第1张图片
【springboot】mongoTemplate增删改查操作_第2张图片

2.2 修改

【springboot】mongoTemplate增删改查操作_第3张图片
【springboot】mongoTemplate增删改查操作_第4张图片

2.3 详情

【springboot】mongoTemplate增删改查操作_第5张图片

2.4 分页

【springboot】mongoTemplate增删改查操作_第6张图片
【springboot】mongoTemplate增删改查操作_第7张图片

2.5 删除

【springboot】mongoTemplate增删改查操作_第8张图片
【springboot】mongoTemplate增删改查操作_第9张图片

你可能感兴趣的:(springboot,mongodb,spring,boot,mongodb)