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

}
相关推荐
愿时间能学会宽恕7 分钟前
SpringBoot后端开发常用工具详细介绍——SpringSecurity认证用户保证安全
spring boot·后端·安全
CodeSheep21 分钟前
稚晖君又开始摇人了,有点猛啊!
前端·后端·程序员
小宁爱Python25 分钟前
Django 从环境搭建到第一个项目
后端·python·django
uzong34 分钟前
深入浅出:画好技术图
后端·架构
向上的车轮42 分钟前
基于Java Spring Boot的云原生TodoList Demo 项目,验证云原生核心特性
java·spring boot·云原生
IT_陈寒43 分钟前
Java性能优化:从这8个关键指标开始,让你的应用提速50%
前端·人工智能·后端
程序员清风44 分钟前
快手一面:为什么要求用Static来修饰ThreadLocal变量?
java·后端·面试
逍遥德1 小时前
Java8 Comparator接口 和 List Steam 排序使用案例
java·spring boot·list·排序算法
chen_ever1 小时前
golang之go modules
开发语言·后端·golang
Victor3561 小时前
Redis(54)Redis的LRU算法是什么?
后端