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
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序员阿明

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值