第五节 springboot集成MongoDB

亮子 2021-06-18 03:58:27 18308 1 1 0

1、创建工程

图片alt

2、添加依赖(可选)

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

3、修改配置文件

server.port=8000
spring.application.name=demo-boot-mongo

spring.data.mongodb.host=127.0.0.1
spring.data.mongodb.port=27017
spring.data.mongodb.database=db_hero

4、创建实体类

package com.shenmazong.demookredis.pojo;

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

/**
 * @author 军哥
 * @version 1.0
 * @description: 英雄实体类
 * @date 2021/12/7 16:39
 */

@Data
@Document(collection = "tb_hero")
public class TbHero {

    // 增加Id注解,生成mongodb的collection对象后,这个注解的字段就是唯一主键,不能重复
    @Id
    private Integer id;

    // 创建索引,但不是唯一索引
    @Indexed(unique = false)
    private String name;
    private Integer age;

    // 给字段起个别名
    // 如果没添加这个注解的话,在mongodb中使用的是work字段名称
    @Field(value ="working" )
    private String work;
}

5、创建测试类

package com.shenmazong.demookredis;

import com.mongodb.client.result.DeleteResult;
import com.shenmazong.demookredis.pojo.TbHero;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
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 java.util.ArrayList;
import java.util.List;

/**
 * @author 军哥
 * @version 1.0
 * @description: MongoDB操作测试类
 * @date 2021/12/7 16:43
 */

@SpringBootTest
public class DemoMongoDbTest {

    @Autowired
    MongoTemplate mongoTemplate;

    /**
     * @description 添加一个文档到集合
     * @author 军哥
     * @date 2021/12/7 20:14
     * @version 1.0
     */
    @Test
    void add() {
        TbHero tbHero = new TbHero();
        tbHero.setId(1);
        tbHero.setName("武松");
        tbHero.setAge(32);
        tbHero.setWork("景阳冈打老虎");

        // save没有就insert,如果有就更新
        mongoTemplate.save(tbHero);

        // insert,如果存在就会报错
        tbHero.setId(2);
        tbHero.setName("吕布");
        tbHero.setAge(32);
        tbHero.setWork("三英战吕布");
        mongoTemplate.insert(tbHero);

        tbHero.setId(3);
        tbHero.setName("赵云");
        tbHero.setAge(32);
        tbHero.setWork("常胜将军");
        mongoTemplate.insert(tbHero);
    }

    /**
     * @description 批量插入
     * @author 军哥
     * @date 2021/12/7 20:45
     * @version 1.0
     */
    @Test
    void insertAll() {
        ArrayList<TbHero> tbHeroes = new ArrayList<>();
        for (int idx = 10; idx < 20; idx++) {
            TbHero tbHero = new TbHero();
            tbHero.setId(idx);
            tbHero.setName("hero"+idx);
            tbHero.setAge(20+idx);
            tbHero.setWork("work,"+idx);

            tbHeroes.add(tbHero);
        }

        mongoTemplate.insertAll(tbHeroes);
    }

    /**
     * @description 查找集合中所有的文档
     * @author 军哥
     * @date 2021/12/7 20:14
     * @version 1.0
     */
    @Test
    void findAll() {
        List<TbHero> all = mongoTemplate.findAll(TbHero.class);
        all.forEach(item-> System.out.println(item));
    }

    /**
     * @description 根据ID或者名字获取文档
     * @author 军哥
     * @date 2021/12/7 20:19
     * @version 1.0
     */
    @Test
    void findById() {
        // 根据ID获取
        Integer id = 2;
        Query query = new Query(Criteria.where("_id").is(id));
        TbHero tbHero = mongoTemplate.findOne(query, TbHero.class);

        System.out.println(tbHero);

    }

    /**
     * @description 根据名字查询
     * @author 军哥
     * @date 2021/12/7 20:47
     * @version 1.0
     */
    @Test
    void findByName() {
        // 根据名字获取
        String name = "武松";
        Query query = new Query(Criteria.where("name").is(name));
        TbHero tbHero = mongoTemplate.findOne(query, TbHero.class);
        System.out.println(tbHero);
    }

    /**
     * @description 根据条件修改文档
     * @author 军哥
     * @date 2021/12/7 20:20
     * @version 1.0
     */
    @Test
    void update() {
        Query query = new Query(Criteria.where("_id").is(1));
        Update update = new Update().set("name", "wusong").set("age", 66);

        // 更新符合条件的第一个
        mongoTemplate.updateFirst(query, update, TbHero.class);

        // 更新符合条件的所有的
//        mongoTemplate.updateMulti(query, update, TbHero.class);

        // 如果没有则增加
//        mongoTemplate.upsert(query, update, TbHero.class);
    }

    /**
     * @description 根据ID删除
     * @author 军哥
     * @date 2021/12/7 20:22
     * @version 1.0
     */
    @Test
    void deleteById() {
        // 根据ID删除
        Query query = new Query(Criteria.where("_id").is(1));
        DeleteResult remove = mongoTemplate.remove(query, TbHero.class);
        System.out.println(remove);
    }

    /**
     * @description 根据对象删除文档
     * @author 军哥
     * @date 2021/12/7 20:27
     * @version 1.0
     */
    @Test
    void deleteByObject() {
        // 根据ID获取对象
        Query query = new Query(Criteria.where("_id").is(19));
        TbHero tbHero = mongoTemplate.findOne(query, TbHero.class);

        // 根据对象删除需要全部属性都要匹配
        DeleteResult remove = mongoTemplate.remove(tbHero);
        System.out.println(remove);
    }

    /**
     * @description 根据条件统计文档的总数
     * @author 军哥
     * @date 2021/12/7 21:34
     * @version 1.0
     */
    @Test
    void getCount() {
        Query query = new Query();
        query.addCriteria(Criteria.where("age").is(32));

        long count = mongoTemplate.count(query, TbHero.class);
        System.out.println(count);
    }

    /**
     * @description 条件查询、排序、分页
     * @author 军哥
     * @date 2021/12/7 21:41
     * @version 1.0
     */

    @Test
    void getList() {
        Query query = new Query();
        Criteria criteria =new Criteria();

        // where age in (18,19) and (id=9 or id=10)
        criteria.orOperator(
                        Criteria.where("age").is(35),
                        Criteria.where("age").is(36)
                );
        query.addCriteria(criteria);
        System.out.println(criteria);

        //计算总数,用于算法分页数
        long count = mongoTemplate.count(query, TbHero.class);
        System.out.println(count);

        //排序逻辑
        query.with(Sort.by(Sort.Order.desc("age")));

        //分页逻辑
        query.skip(1).limit(1);

        List<TbHero> tbHeroes = mongoTemplate.find(query, TbHero.class);
        tbHeroes.forEach(item-> System.out.println(item));
    }
}