当先锋百科网

首页 1 2 3 4 5 6 7

一 集成简介

spring-data-mongodb 提供了 MongoTemplate 与 MongoRepository 两种方式访问 mongodb,MongoRepository 操作简单,MongoTemplate 操作灵活,我们在项目中可以灵活使用这两种方式操作 mongodb,MongoRepository 的缺点是不够灵活,MongoTemplate 正好可以弥补不足。

二 搭建开发环境

1 初始化工程

使用 Spring Initializr 快速初始化一个 Spring Boot 工程。

2 引入依赖

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

    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
    </dependency>

    <dependency>
        <groupId>joda-time</groupId>
        <artifactId>joda-time</artifactId>
        <version>2.10.1</version>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
        <exclusions>
            <exclusion>
                <groupId>org.junit.vintage</groupId>
                <artifactId>junit-vintage-engine</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
</dependencies>

3 添加配置

spring.data.mongodb.uri=mongodb://127.0.0.1:27017/test

三 基于MongoTemplate 开发 CRUD

1 添加实体

package com.cakin.mongodb.entity;

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

@Data
@Document("User")
public class User {
    @Id
    private String id;
    private String name;
    private Integer age;
    private String email;
    private String createDate;
}

2 实现

常用方法

  • 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对象

创建一个query对象(用来封装所有条件对象),再创建一个criteria对象(用来构建条件)

  • 精准条件:criteria.and("key").is("条件")

  • 模糊条件:criteria.and("key").regex("条件")

  • 封装条件:query.addCriteria(criteria)

  • 大于(创建新的criteria):Criteria gt = Criteria.where("key").gt("条件")

  • 小于(创建新的criteria):Criteria lt = Criteria.where("key").lt("条件")

  • Query.addCriteria(new Criteria().andOperator(gt,lt));

  • 一个 query 中只能有一个 andOperator()。其参数也可以是 Criteria 数组。

  • 排序 :query.with(new Sort(Sort.Direction.ASC, "age"). and(new Sort(Sort.Direction.DESC, "date")))

3 测试类

package com.cakin.demomptest;

import com.cakin.mongodb.entity.User;
import com.mongodb.client.result.DeleteResult;
import com.mongodb.client.result.UpdateResult;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
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 java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

@SpringBootTest
class DemomogoApplicationTests {

    @Autowired
    private MongoTemplate mongoTemplate;

    // 添加
    @Test
    public void createUser() {
        User user = new User();
        user.setAge(20);
        user.setName("test");
        user.setEmail("[email protected]");
        User user1 = mongoTemplate.insert(user);
        System.out.println(user1);
    }

    // 查询所有
    @Test
    public void findUser() {
        List<User> userList = mongoTemplate.findAll(User.class);
        System.out.println(userList);
    }

    // 根据 id 查询
    @Test
    public void getById() {
        User user =
                mongoTemplate.findById("616a8369f2aa952ed755d08f", User.class);
        System.out.println(user);
    }

    // 条件查询
    @Test
    public void findUserList() {
        Query query = new Query(Criteria
                .where("name").is("test")
                .and("age").is(20));
        List<User> userList = mongoTemplate.find(query, User.class);
        System.out.println(userList);
    }

    // 模糊查询
    @Test
    public void findUsersLikeName() {
        String name = "est";
        String regex = String.format("%s%s%s", "^.*", name, ".*$");
        Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
        Query query = new Query(Criteria.where("name").regex(pattern));
        List<User> userList = mongoTemplate.find(query, User.class);
        System.out.println(userList);
    }

    // 分页查询
    @Test
    public void findUsersPage() {
        String name = "est";
        int pageNo = 1;
        int pageSize = 10;

        Query query = new Query();
        String regex = String.format("%s%s%s", "^.*", name, ".*$");
        Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
        query.addCriteria(Criteria.where("name").regex(pattern));
        int totalCount = (int) mongoTemplate.count(query, User.class);
        List<User> userList = mongoTemplate.find(query.skip((pageNo - 1) * pageSize).limit(pageSize), User.class);

        Map<String, Object> pageMap = new HashMap<>();
        pageMap.put("list", userList);
        pageMap.put("totalCount", totalCount);
        System.out.println(pageMap);
    }

    // 修改
    @Test
    public void updateUser() {
        User user = mongoTemplate.findById("616a8369f2aa952ed755d08f", User.class);
        user.setName("test_1");
        user.setAge(25);
        user.setEmail("[email protected]");
        Query query = new Query(Criteria.where("_id").is(user.getId()));
        Update update = new Update();
        update.set("name", user.getName());
        update.set("age", user.getAge());
        update.set("email", user.getEmail());
        UpdateResult result = mongoTemplate.upsert(query, update, User.class);
        long count = result.getModifiedCount();
        System.out.println(count);
    }

    // 删除操作
    @Test
    public void delete() {
        Query query =
                new Query(Criteria.where("_id").is("616a8369f2aa952ed755d08f"));
        DeleteResult result = mongoTemplate.remove(query, User.class);
        long count = result.getDeletedCount();
        System.out.println(count);
    }
}