spring boot 整合mongodb

1、安装依赖

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

2、配置数据库连接

spring:
  data:
    mongodb:
      host: localhost
      port: 27017
      username: xxxxxx
      password: xxxxxx
      database: xxxxxx
      authentication-database: admin

3、新建实体类

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

@Data
//代表集合名称
@Document("myCollection")
public class MyCollection {
    @Id
    private String id;
    private String name;
    private Integer age;
    private String sex;
}

4、调用方法

4.1 方法一

package com.example.springboot3test.controller;

import com.example.springboot3test.entity.MyCollection;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
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.web.bind.annotation.*;

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

@RestController
@RequestMapping("/test")
public class TestController {

    @Resource
    private MongoTemplate mongoTemplate;//引入的对象
    
    //查询所有不带条件
    @GetMapping("/findAllData")
    public List<MyCollection> findAllData(){
        return mongoTemplate.findAll(MyCollection.class);
    }

    //根据Id查询
    @GetMapping("/findDataById/{id}")
    public MyCollection findDataById(@PathVariable("id") String id){
        return mongoTemplate.findById(id,MyCollection.class);
    }

    //where条件查询
    @PostMapping("/findByWhere")
    public List<MyCollection> findByWhere(@RequestBody MyCollection myCollection){
        Query query=new Query(Criteria.where("name").is(myCollection.getName()).
                and("age").gte(myCollection.getAge())
        );
        return mongoTemplate.find(query,MyCollection.class);
    }

    //模糊查询
    @PostMapping("/findByLike")
    public List<MyCollection> findByLike(@RequestBody MyCollection myCollection){
        String regex = String.format("%s%s%s", "^.*", myCollection.getName(), ".*$");
        Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
        Query query=new Query(Criteria.where("name").regex(pattern));
        return mongoTemplate.find(query,MyCollection.class);
    }
    //插入
    @PostMapping("/insertMongodb")
    public String insertMongodb(@RequestBody MyCollection myCollection){
        mongoTemplate.insert(myCollection);
        return "OK";
    }

    //批量插入
    @PostMapping("/insertBatchsMongodb")
    public String insertBatchsMongodb(@RequestBody List<MyCollection> list){
        mongoTemplate.insertAll(list);
        return "OK";
    }

    //更新
    @PostMapping("/updateMongodb")
    public String updateMongodb(@RequestBody MyCollection myCollection){
        Query query=new Query(
                Criteria.where("age").gte(38)
        );
        Update update=new Update();
        update.set("name",myCollection.getName());
        //单条更新
        //mongoTemplate.upsert(query,update,MyCollection.class);
        //批量更新
        mongoTemplate.updateMulti(query,update,MyCollection.class);
        return "OK";
    }

    //删除根据条件
    @GetMapping("/deleteMongodb/{age}")
    public String deleteMongodb(@PathVariable("age") Long age){
        Query query=new Query(
                Criteria.where("age").gte(age)
        );
        mongoTemplate.remove(query,MyCollection.class);
        return "OK";
    }
}

注:其中的常用方法如下

常用方法
mongoTemplate.findAll(User.class): 查询User文档的全部数据
mongoTemplate.findById(<id>, User.class): 查询User文档id为id的数据
mongoTemplate.find(query, User.class);: 根据query内的查询条件查询
mongoTemplate.upsert(query, update, User.class): 修改
mongoTemplate.remove(query, User.class): 删除
mongoTemplate.insert(User): 新增

Query对象
1、创建一个query对象(用来封装所有条件对象),再创建一个criteria对象(用来构建条件)
2、 精准条件:criteria.and("key").is("条件")
      模糊条件:criteria.and("key").regex("条件")
3、封装条件:query.addCriteria(criteria)
4、大于(创建新的criteria):Criteria gt = Criteria.where("key").gt("条件")
     小于(创建新的criteria):Criteria lt = Criteria.where("key").lt("条件")
5、Query.addCriteria(new Criteria().andOperator(gt,lt));
6、一个query中只能有一个andOperator()。其参数也可以是Criteria数组。
7、排序 :query.with(new Sort(Sort.Direction.ASC, "age"). and(new Sort(Sort.Direction.DESC, "date")))

Criteria查询条件类常用方法

//声明定义查询条件,且为静态方法
where(String key)
//与操作
and(String key)
//正则表达式,即可为模糊查询
regex(String re)
//包含
in(Object... o)    
//大于
gt(Object o)
//大于等于
gte(Object o)
//等于
is(Object o)
//小于
lt(Object o)
//小于等于
lte(Object o) 
//非
not()
//创建与操作
andOperator(Criteria... criteria) 

4.2 方法二 spring Data 方式

spring Data提供了对mongodb数据访问的支持,我们只需要继承MongoRepository类,按照Spring Data规范就可以了。

当需要根据实体类中的属性查询时,MongoRepository提供的方法已经不能满足,我们需要在PersonRepository仓库中定义方法,定义方法名的规则为:find + By + 属性名(首字母大写);如果为删除,则delete + By + 属性名(首字母大写)

step1 新建MyCollectionRepository接口

package com.example.springboot3test.dao;

import com.example.springboot3test.entity.MyCollection;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface MyCollectionRepository extends MongoRepository<MyCollection,String> {
    //当需要根据实体类中的属性查询时,MongoRepository提供的方法已经不能满足,我们需要在PersonRepository仓库中定义方法,定义方法名的规则为:find + By +
    // 属性名(首字母大写),如:根据姓名查询Person。
    //仓库中添加的方法

    //根据名称查询
    List<MyCollection> findByName(String name);
    //模糊查询
    List<MyCollection> findByNameLike(String name);

    //模糊查询
    List<MyCollection> findByNameLikeAndAgeGreaterThanEqual(String name,Integer age);

    //根据条件删除
    void deleteByAgeGreaterThanEqual(Integer age);

    //分页查询
    Page<MyCollection> findByNameLike(String name, Pageable pageable);

}

step2 、测试代码

package com.example.springboot3test.controller;

import com.example.springboot3test.dao.MyCollectionRepository;
import com.example.springboot3test.entity.MyCollection;
import jakarta.annotation.Resource;

import org.springframework.data.domain.Page;


import org.springframework.data.domain.PageRequest;
import org.springframework.web.bind.annotation.*;

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

@RestController
@RequestMapping("/mongodb")
public class TestMongodbController {
    @Resource
    private MyCollectionRepository myCollectionRepository;

    //插入单条
    @PostMapping("/insertMongodb")
    public String insertMongodb(@RequestBody MyCollection myCollection){
        myCollectionRepository.insert(myCollection);
        return "OK";
    }

    //批量插入
    @PostMapping("/insertMongodbBatchs")
    public String insertMongodbBatchs(@RequestBody List<MyCollection> myCollection){
        myCollectionRepository.insert(myCollection);
        return "OK";
    }

    //更新
    @PostMapping("/updateMongodb")
    public String updateMongodb(@RequestBody MyCollection myCollection){
        myCollectionRepository.save(myCollection);
        //myCollectionRepository.insert(myCollection);
        return "OK";
    }

    //删除
    @GetMapping("/deleteMongodbById/{id}")
    public String deleteMongodbById(@PathVariable("id") String id){
        myCollectionRepository.deleteById(id);
        return "OK";
    }

    //根据条件删除
    @GetMapping("/deleteMongodbByAge/{age}")
    public String deleteMongodbByAge(@PathVariable("age") Integer age){
        myCollectionRepository.deleteByAgeGreaterThanEqual(age);
        return "OK";
    }

    //查询所有
    @GetMapping("/findAll")
    public List<MyCollection> findAll(){
        return myCollectionRepository.findAll();
    }

    //根据Id进行查询
    @GetMapping("/findById/{id}")
    public MyCollection findById(@PathVariable("id") String id){
        return myCollectionRepository.findById(id).get();
    }

    //条件查询
    @PostMapping("/findQuery")
    public List<MyCollection> findQuery(@RequestBody MyCollection myCollection){
        return myCollectionRepository.findByName(myCollection.getName());
    }

    //分页查询
    @PostMapping("/findQueryByPage")
    public Page<MyCollection> findQueryByPage(@RequestBody Map<String,String> params){
        //分页参数
        Integer page=Integer.valueOf(params.get("page"));
        Integer pageSize=Integer.valueOf(params.get("pageSize"));
        PageRequest pageRequest = PageRequest.of(page-1,pageSize);
        return myCollectionRepository.findByNameLike(params.get("name"),pageRequest);
    }

    //模糊匹配
    @PostMapping("/findLike")
    public List<MyCollection> findLike(@RequestBody MyCollection myCollection){
        return myCollectionRepository.findByNameLike(myCollection.getName());//单个模糊查询
    }

    //模糊匹配
    @PostMapping("/findLikeAnd")
    public List<MyCollection> findLikeAnd(@RequestBody MyCollection myCollection){
        //多个条件模糊查询
        return myCollectionRepository.findByNameLikeAndAgeGreaterThanEqual(myCollection.getName(),myCollection.getAge());
    }

}
相关推荐
叫我:松哥2 分钟前
基于Python flask的医院管理学院,医生能够增加/删除/修改/删除病人的数据信息,有可视化分析
javascript·后端·python·mysql·信息可视化·flask·bootstrap
海里真的有鱼5 分钟前
Spring Boot 项目中整合 RabbitMQ,使用死信队列(Dead Letter Exchange, DLX)实现延迟队列功能
开发语言·后端·rabbitmq
工业甲酰苯胺16 分钟前
Spring Boot 整合 MyBatis 的详细步骤(两种方式)
spring boot·后端·mybatis
新知图书1 小时前
Rust编程的作用域与所有权
开发语言·后端·rust
wn5312 小时前
【Go - 类型断言】
服务器·开发语言·后端·golang
bjzhang752 小时前
SpringBoot开发——集成Tess4j实现OCR图像文字识别
spring boot·ocr·tess4j
flying jiang2 小时前
Spring Boot 入门面试五道题
spring boot
小菜yh2 小时前
关于Redis
java·数据库·spring boot·redis·spring·缓存
希冀1232 小时前
【操作系统】1.2操作系统的发展与分类
后端
GoppViper3 小时前
golang学习笔记29——golang 中如何将 GitHub 最新提交的版本设置为 v1.0.0
笔记·git·后端·学习·golang·github·源代码管理