MongoDB连接工具

  • Navicat for MongoDB

官网下载地址:http://www.navicat.com.cn/download/navicat-for-mongodb
老牌的数据库管理工具,支持多种数据库的集成,已集成 MongoDB 类型,属于付费型管理工具。好处是用会了一个 DB 版的 Navicat,所有 DB 版都会很顺手,维持一套操作习惯,如果再肌肉记忆一些快捷键,会更加高效。

MongoDB集成SpringBoot

1 官方文档

Spring Data MongoDB官方文档
https://spring.io/projects/spring-data-mongodb

Spring Boot与Spring Data MongoDB版本兼容关系
https://docs.spring.io/spring-data/mongodb/docs/3.2.4/reference/html/#compatibility.matrix

注意事项
springboot与spring data mongoDB版本兼容问题,不同版本之间互不兼容。

2 引入依赖

<parent>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-parent</artifactId>
   <version>2.5.4</version>
   <relativePath/> <!-- lookup parent from repository -->
</parent>

<dependencies>    
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-data-mongodb</artifactId>
    </dependency>
  <!--mongodb Java驱动-->
    <dependency>
    <groupId>org.mongodb</groupId>
        <artifactId>mongo-java-driver</artifactId>
        <version>3.12.10</version>
    </dependency>
</dependencies>

3 配置参数

在application.properties配置文件中

spring.data.mongodb.uri= mongodb://127.0.0.1:27017/mongo
log4j.category.org.springframework.data.mongodb=DEBUG
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %40.40c:%4L - %m%n

4 代码实现

Repository和Template的选择。SpringData为我们提供了两种方式对数据库进行操作,第一种是继承Repository接口,第二种是直接使用Template的方式对数据进行操作。
第一种方式,直接继承xxxRepository接口,其最终将会继承Repository标记接口,我们可以不必自己写实现类,轻松实现增删改查、分页、排序操作,但是对于比较复杂的查询,使用起来就比较费力。
第二种方式,直接使用xxxTemplate,这需要自己写实现类,但是这样增删改查可以自己控制,对于复杂查询,用起来得心应手。

EmployeeController

package com.jerry.market.controller;

import com.jerry.market.entity.Response;
import com.jerry.market.service.EmployeeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * 员工控制器
 *
 * @author zrj
 * @since 2022/3/29
 **/
@Slf4j
@RestController
@RequestMapping("/employee")
@Api(tags = "EmployeeController", description = "员工控制器")
public class EmployeeController {
    @Resource
    private EmployeeService employeeService;

    /**
     * 新增接口
     */
    @GetMapping("/create")
    @ApiOperation("新增接口")
    public Response create() {
        return Response.success(employeeService.create());
    }

    /**
     * 更新接口
     */
    @GetMapping("/update")
    @ApiOperation("更新接口")
    public Response update() {
        return Response.success(employeeService.update());
    }

    /**
     * 删除接口
     */
    @GetMapping("/delete")
    @ApiOperation("删除接口")
    public Response delete() {
        return Response.success(employeeService.delete());
    }

    /**
     * 查询接口
     */
    @GetMapping("/select")
    @ApiOperation("查询接口")
    public Response select() {
        return Response.success(employeeService.select());
    }
}

Employee

package com.jerry.market.entity;

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

/**
 * @author zrj
 * @since 2022/3/29
 **/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Document(collection = "employee") //通过collection参数指定当前实体类对应的文档
public class Employee {
    @Id //用来标识主键
    private String id;

    private String name;

    @Field("pwd") //给字段起别名
    private String password;

    //@Indexed 用于声明字段需要索引
}

EmployeeRepository

package com.jerry.market.repository;

import com.jerry.market.entity.Employee;
import org.springframework.data.mongodb.repository.MongoRepository;

/**
 * 员工Dao
 * 定义Dao接口继承MongoRepository<实体类型,主键类型>
 *
 * @author zrj
 * @since 2022/3/29
 **/
public interface EmployeeRepository extends MongoRepository<Employee, String> {
}

Response

package com.jerry.market.entity;

import lombok.Data;
import org.springframework.stereotype.Component;

/**
 * 响应对象
 *
 * @author zrj
 * @since 2022/3/23
 **/
@Data
@Component
public class Response<T> {
    /**
     * 状态码
     */
    private static String successCode = "200";
    private static String successMsg = "执行成功";
    private static String failCode = "500";
    private static String failMsg = "执行失败";

    /**
     * 提示消息
     */
    private String message;

    /**
     * 状态码
     */
    private String code;

    /**
     * 具体返回的数据
     */
    private T data;

    public Response() {
    }

    private Response(String code, String msg) {
        this.message = msg;
        this.code = code;
    }

    private Response(String code, String message, T data) {
        this.message = message;
        this.code = code;
        this.data = data;
    }

    /**
     * 返回成功Response对象
     */
    public static <T> Response<T> success(T data) {
        return new Response<>(successCode, successMsg, data);
    }

    public static <T> Response<T> success(String successMessage, T data) {
        return new Response<>(successCode, successMessage, data);
    }

    public static <T> Response<T> success(String code, String successMessage, T data) {
        return new Response<>(code, successMessage, data);
    }

    /**
     * 返回错误Response对象
     */
    public static <T> Response<T> fail(String failMsg) {
        return new Response<>(failCode, failMsg);
    }

    public static <T> Response<T> fail(String failCode, String failMsg) {
        return new Response<>(failCode, failMsg);
    }

    public static <T> Response<T> fail(String failCode, String failMsg, T data) {
        return new Response<>(failCode, failMsg, data);
    }
}

EmployeeServiceImpl

package com.jerry.market.service.impl;

import cn.hutool.core.util.IdUtil;
import com.jerry.market.entity.Employee;
import com.jerry.market.repository.EmployeeRepository;
import com.jerry.market.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
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.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * 员工接口实现类
 * 第一种方式,直接继承xxxRepository接口,其最终将会继承Repository标记接口,我们可以不必自己写实现类,轻松实现增删改查、分页、排序操作,但是对于比较复杂的查询,使用起来就比较费力。
 * 第二种方式,直接使用xxxTemplate,这需要自己写实现类,但是这样增删改查可以自己控制,对于复杂查询,用起来得心应手。
 *
 * @author zrj
 * @since 2022/3/29
 **/
@Slf4j
@Service
public class EmployeeServiceImpl implements EmployeeService {

    @Resource
    private EmployeeRepository employeeRepository;

    @Resource
    private MongoTemplate mongoTemplate;

    /**
     * 新增
     *
     * @return String
     */
    @Override
    public String create() {
        //第一种方式,直接继承xxxRepository接口
        Employee employee = Employee.builder().id("1").name("张三").password("123").build();
        employeeRepository.save(employee);
        log.info("第一种方式新增成功,employee:" + employee);

        //第二种方式,直接使用xxxTemplate
        //注意:id不能重复。MongoWriteException: E11000 duplicate key error collection: mongo.employee index: _id_ dup key: { _id: "3" }
        Employee employee2 = Employee.builder().id(IdUtil.simpleUUID()).name("李四").password("123").build();
        mongoTemplate.insert(employee2);
        log.info("第二种方式新增成功,employee:" + employee2);

        log.info("【员工接口】新增成功");
        return "新增成功";
    }

    /**
     * 更新
     *
     * @return String
     */
    @Override
    public String update() {
        //第一种方式,直接继承xxxRepository接口
        Employee employee = Employee.builder().id("1").name("张更新").password("666").build();
        employeeRepository.save(employee);

        //第二种方式,直接使用xxxTemplate
        Query query = Query.query(Criteria.where("id").is("2").and("name").is("王小二"));
        Update update = Update.update("name", "王更新");
        mongoTemplate.updateFirst(query, update, Employee.class);

        log.info("【员工接口】更新成功");
        return "更新成功";
    }

    /**
     * 删除
     *
     * @return String
     */
    @Override
    public String delete() {
        //第一种方式,直接继承xxxRepository接口
        employeeRepository.deleteById("1");

        //第二种方式,直接使用xxxTemplate
        Query query = Query.query(Criteria.where("id").is("2"));
        mongoTemplate.remove(query, Employee.class);

        log.info("【员工接口】删除成功");
        return "删除成功";
    }

    /**
     * 查询
     *
     * @return String
     */
    @Override
    public List<Employee> select() {
        //第一种方式,直接继承xxxRepository接口
        List<Employee> employeeList = employeeRepository.findAll();
        System.out.println("第一种方式,employeeList:" + employeeList);

        //第二种方式,直接使用xxxTemplate
        List<Employee> employeeLists = this.mongoTemplate.findAll(Employee.class);
        System.out.println("第二种方式,employeeList:" + employeeLists);

        log.info("【员工接口】查询成功");
        return employeeLists;
    }
}

EmployeeService

package com.jerry.market.service;

import com.jerry.market.entity.Employee;

import java.util.List;

/**
 * @author zrj
 * @since 2022/3/29
 **/
public interface EmployeeService {
    /**
     * 新增
     * @return String
     */
    String create();

    /**
     * 更新
     * @return String
     */
    String update();

    /**
     * 删除
     * @return String
     */
    String delete();

    /**
     * 查询
     * @return String
     */
    List<Employee> select();

}
Last modification:September 23rd, 2022 at 02:23 pm
If you think my article is useful to you, please feel free to appreciate