欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

SpringBoot工程下MongoDB增删改查,以及复杂查询和更新

程序员文章站 2022-03-26 21:21:10
1.数据库设计结构{ "_id": ObjectId("5f05ab4484cd013081699682"), "name": "小明", "age": 29, "gender": "男", "phone": "15914922663", "friends": [ { "name": "小白", "age": NumberInt("27"), "gender": "女...

1.数据库设计结构

{
    "_id": ObjectId("5f05ab4484cd013081699682"),
    "name": "小明",
    "age": 29,
    "gender": "男",
    "phone": "15914922663",
    "friends": [
        {
            "name": "小白",
            "age": NumberInt("27"),
            "gender": "女",
            "phone": "16620055669",
            "hobby": [
                "画画",
                "旅行",
                "弹钢琴",
                "古筝"
            ]
        },
        {
            "name": "隔壁老王",
            "age": NumberInt("98"),
            "gender": "男",
            "phone": "19920066447",
            "hobby": [
                "王者农药",
                "吃鸡",
                "射击",
                "看书",
                "格斗",
                "动画制作后期处理"
            ]
        },
        {
            "name": "张三",
            "age": NumberInt("28"),
            "gender": "男",
            "phone": "17266989541",
            "hobby": [
                "听音乐",
                "唱歌",
                "羽毛球",
                "ewgsd"
            ]
        }
    ]
}

小明有name,age,gender,phone这些属性,他的朋友有3个,分别是小白、隔壁老王、张三,他的朋友也有name,age,gender,phone这些属性,并且有hobby这个属性

 

2.创建SpringBoot工程,并开始编写代码

在pom.xml中添加这两个依赖

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.8</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-mongodb</artifactId>
        </dependency>

配置application.yml文件

server:
  port: 9999

###username是用户名,password是密码,databasename是数据库名,最重要的是authdatabase,这是验证数据库名称,必须填
spring:
  data:
    mongodb:
      uri: mongodb://username:password@47.101.102.103:27017/databasename?authSource=authdatabase

 

SpringBoot工程下MongoDB增删改查,以及复杂查询和更新

创建bean包,在此包创建Person类和Friend类

Person类:

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

import java.util.List;


@Data    //自动生成getter,setter方法
@NoArgsConstructor    //无参构造器
@AllArgsConstructor    //全参构造器
@Document(collection = "Person")    //指定mongodb的哪个collection
public class Person {
    @Id    //指定主键
    private String id;
    private String name;
    private Integer age;
    private String gender;
    private String phone;
    private List<Friend> friends;

}

Friend类:

import lombok.Data;
import java.util.List;

@Data
public class Friend {
    //注意,下面的属性名必须要和数据库的字段一致
    private String name;
    private Integer age;
    private String gender;
    private String phone;
    private List<String> hobby;
}

 

创建controller包,在此包下创建FriendMongoDBController类,里面包含了所有增删改查的方法,以及复杂查询更新的方法

import com.example.springcloud_mongodb_test1.bean.Friend;
import com.example.springcloud_mongodb_test1.bean.Person;
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.ArrayList;
import java.util.List;


@RestController
public class FriendMongoDBController {
    @Autowired
    MongoTemplate mongoTemplate;
    //查询所有记录
    //测试地址http://127.0.0.1:9999/findAllPerson
    @GetMapping("/findAllPerson")
    public List<Person> getAllPerson(){
        return mongoTemplate.findAll(Person.class);
    }

    //根据id查询记录
    //测试地址http://127.0.0.1:9999/findPersonById/xxxxxid
    @GetMapping("/findPersonById/{id}")
    public List<Person> getPersonById(@PathVariable("id")String id){
        Query query = new Query();
        query.addCriteria(Criteria.where("id").is(id));
        return mongoTemplate.find(query,Person.class);

    }

    //根据id查询一个Person的朋友
    //测试地址http://127.0.0.1:9999/findFriendsById/xxxxxid
    @GetMapping("/findFriendsById/{id}")
    public List<Friend> getFriendsById(@PathVariable("id")String id){
        Query query = new Query();
        query.addCriteria(Criteria.where("id").is(id));
        List<Person> personList = mongoTemplate.find(query,Person.class);
        List<Friend> friendList = personList.get(0).getFriends();
        return friendList;
    }

    //根据姓名模糊查询
    //测试地址http://127.0.0.1:9999/findBlurByName
    @GetMapping("/findBlurByName")
    public List<Person> getBlurByName(){
        Query query = new Query();
        query.addCriteria(Criteria.where("name").regex(".*小.*"));
        List<Person> personList = mongoTemplate.find(query,Person.class);
        return personList;
    }

    //多条件查询,查询年龄大于90小于120的Person
    //测试地址http://127.0.0.1:9999/findAgeField/90/120
    @GetMapping("/findAgeField/{gt}/{lt}")
    public List<Person> getAgeField(@PathVariable("gt")Integer gt,@PathVariable("lt")Integer lt){
        Query query = new Query();
        Criteria criteria = new Criteria();
        criteria.andOperator(
          Criteria.where("age").gt(gt),
          Criteria.where("age").lt(lt)
        );
        query.addCriteria(criteria);
        List<Person> personList = mongoTemplate.find(query,Person.class);
        return personList;
    }

    //多条件查询,与或条件并存,查询年龄大于90小于120的或者姓名包括有"小"字的Person
    //测试地址http://127.0.0.1:9999/findAgeFieldOrName/90/120/小
    @GetMapping("/findAgeFieldOrName/{gt}/{lt}/{name}")
    public List<Person> getAgeFieldOrName(@PathVariable("gt")Integer gt,@PathVariable("lt")Integer lt,@PathVariable("name")String name){
        Query query = new Query();
        Criteria criteria = new Criteria();

        criteria.orOperator(
                new Criteria().andOperator(
                        Criteria.where("age").gt(gt),
                        Criteria.where("age").lt(lt)
                ),
                Criteria.where("name").regex(".*"+name+".*")
        );
        query.addCriteria(criteria);
        List<Person> personList = mongoTemplate.find(query,Person.class);
        return personList;
    }

    //更新一个Person的某个朋友的信息,例如更新小明的朋友张三的爱好,我们为她添加一个爱好,以更新数据
    //必须先把url粘贴到浏览器,然后复制url,粘贴到postman去发送post请求,我们将会发现postman显示的url的中文部分是一串乱码
    //测试地址http://127.0.0.1:9999/updateFriendHobbyByName/小明/张三/爱好xxx
    @RequestMapping("/updateFriendHobbyByName/{name}/{friend_name}/{hobby}")
    public String updateFriendHobbyByName(@PathVariable("name")String name,@PathVariable("friend_name")String friend_name,@PathVariable("hobby")String hobby){
        Query query = new Query();
        query.addCriteria(Criteria.where("name").is(name));
        List<Person> personList = mongoTemplate.find(query,Person.class);
        List<Friend> friendList = personList.get(0).getFriends();

        for(int i=0;i<friendList.size();i++){
            if(friendList.get(i).getName().equals(friend_name)){
                List<String> hobbyList = friendList.get(i).getHobby();
                hobbyList.add(hobby);
                break;
            }

        }
        Update update = new Update().set("friends",friendList);
        mongoTemplate.updateFirst(query,update,Person.class);


        return null;
    }

    //插入一个新的Person
    //测试地址http://127.0.0.1:9999/addOnePerson
    @RequestMapping("/addOnePerson")
    public Person addOnePerson(){
        Person person = new Person();
        person.setName("星爷");
        person.setAge(92);
        person.setGender("男");
        person.setPhone("16655966754");
        List<Friend> friendList = new ArrayList<>();
        Friend friend = new Friend();
        friend.setName("哈莉");
        friend.setAge(18);
        friend.setGender("女");
        friend.setPhone("66955421563");
        List<String> hobbyList = new ArrayList<>();
        for(int i=1;i<5;i++){
            hobbyList.add("爱好"+Integer.toString(i));
        }
        friend.setHobby(hobbyList);
        friendList.add(friend);
        person.setFriends(friendList);
        mongoTemplate.insert(person);
        return person;
    }

    //根据删除一个Person
    //测试地址http://127.0.0.1:9999/delOnePerson/xxxid
    @RequestMapping("/delOnePerson/{id}")
    public void delOnePerson(@PathVariable("id")String id){
        Query query = new Query();
        query.addCriteria(Criteria.where("id").is(id));
        mongoTemplate.remove(query, Person.class);
    }


}

创建config包,并创建MongoConfig类(插入数据的时候避免生成_class字段)

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.convert.CustomConversions;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.core.convert.DbRefResolver;
import org.springframework.data.mongodb.core.convert.DefaultDbRefResolver;
import org.springframework.data.mongodb.core.convert.DefaultMongoTypeMapper;
import org.springframework.data.mongodb.core.convert.MappingMongoConverter;
import org.springframework.data.mongodb.core.mapping.MongoMappingContext;

@Configuration
public class MongoConfig {

    @Bean
    public MappingMongoConverter mappingMongoConverter(MongoDbFactory factory, MongoMappingContext context, BeanFactory beanFactory) {
        DbRefResolver dbRefResolver = new DefaultDbRefResolver(factory);
        MappingMongoConverter mappingConverter = new MappingMongoConverter(dbRefResolver, context);
        try {
            mappingConverter.setCustomConversions(beanFactory.getBean(CustomConversions.class));
        } catch (NoSuchBeanDefinitionException ignore) {
        }

        // Don't save _class to mongo
        mappingConverter.setTypeMapper(new DefaultMongoTypeMapper(null));

        return mappingConverter;
    }

}

 

mongodb最实用的增删改查的方法到此结束,谢谢大家浏览此文章!

 

本文地址:https://blog.csdn.net/Xeon_CC/article/details/107216249