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());
    }

}
相关推荐
码事漫谈41 分钟前
以后人人都可以成为导演
后端
Resean02231 小时前
Spring 源码分析(二)配置类的解析与扫描
java·后端·spring
一只爱撸猫的程序猿1 小时前
五周、两个开源仓库、九次拦截之后:AI 时代程序员缺的到底是什么
人工智能·后端·开源
北城笑笑2 小时前
Vue 110 ,若依SSE流式接口限次空500排查与解决
前端·javascript·vue.js·后端·vue
ServBay3 小时前
Local harness 将退役,VS Code 本地开发要不要搬到云端?
后端·ai编程·visual studio code
ashiho3 小时前
【LeetCode hot 100】3. 无重复字符的最长子串 (三种解法)
java·数据结构·后端·算法·leetcode·滑动窗口
张一凡934 小时前
你的 AGENTS.md,真的管到模型写代码了吗?
前端·后端·agent
00后程序员4 小时前
iOS 实时活动怎么开发,Windows 上用 KXBuild 和 ActivityKit 写灵动岛
后端·ios
程序员cxuan4 小时前
推荐 10 个 WorkBuddy 中的邪修用法
人工智能·后端·程序员
Bacon5 小时前
给项目做一次"全身 CT":Agent Skills 生态里的代码体检全链路
前端·人工智能·后端