• 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏吧

关于MongoDB的简单理解(三)–Spring Boot篇

开发技术 开发技术 4周前 (01-31) 14次浏览

一、前言

  Spring Boot集成MongoDB非常简单,主要为加依赖加配置编码

二、说明

环境说明:

  • JDK版本为15(1.8+即可)
  • Spring Boot 2.4.1

三、集成步骤

3.1 添加依赖

<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-data-mongodb -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-mongodb</artifactId>
    <version>2.4.1</version>
</dependency>

3.2添加配置

spring:
  # mongo连接
  data:
    mongodb:
      uri: mongodb://mydb:mydb@127.0.0.1:27017/mydb

四、案例

4.1 基于MongoRepository实现对MongoDB的操作

4.1.1 新建客户实体类

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
import org.springframework.data.annotation.Id;

@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@NoArgsConstructor                 //无参构造
@AllArgsConstructor                 //有参构造
// 客户
public class Customer {

    // 主键ID
    // 此种方式ID需要自己设定
    @Id
    private String id;

//    // 主键ID
//    // 采用此种方式会自动生成ID
//    private ObjectId id;

    // 名字
    private String firstName;

    // 姓氏
    private String lastName;
}

4.1.2 新建客户仓库并实现MongoDB仓库

import com.ruiyicloud.bbfbusiness.entity.mongo.Customer;
import org.springframework.data.mongodb.repository.MongoRepository;

import java.util.List;


public interface CustomerRepository extends MongoRepository<Customer, String> {

    /**
     * 根据名字查找客户
     * @param firstName 名字
     * @return
     */
    Customer findByFirstName(String firstName);

    /**
     * 根据姓氏查找客户
     * @param lastName 姓氏
     * @return
     */
    List<Customer> findByLastName(String lastName);

}

4.1.3 创建控制器,对接口方法进行测试

import com.ruiyicloud.bbfbusiness.entity.mongo.Customer;
import com.ruiyicloud.bbfbusiness.service.mongo.CustomerRepository;
import com.ruiyicloud.comm.result.Result;
import com.ruiyicloud.comm.result.ResultGenerator;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Optional;

import static com.ruiyicloud.comm.utils.check.CheckUtil.notNull;


/**
 * <p>
 * MongoDB相关操作
 * </p>
 *
 * @author wanggx_ruiyi
 * @since 2021-01-19
 */
@Api(description="MongoDB相关操作",tags={"MongoDB"})
@RestController
@RequestMapping("/api/v1/mongo/mongoTest")
public class MongoTestController {
    @Resource
    private CustomerRepository customerRepository;

    @InitBinder
    protected void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
    }

    /**
     * @create wanggx_ruiyi 2021-01-19 新增客户信息
     * @param customer 客户模型
     * @return
     */
    @ApiOperation(value="新增",notes = "新增")
    @PostMapping("/add")
    public Result<Customer> add(@ApiParam(name = "customer", value = "客户模型", required = true) @RequestBody Customer customer) {

        notNull(customer, "输入参数不能为空");

        return ResultGenerator.genSuccessResult(customerRepository.save(customer));
    }

    /**
     * @create wanggx_ruiyi 2021-01-19 批量新增客户信息
     * @param customerList 客户模型列表
     * @return
     */
    @ApiOperation(value="批量新增",notes = "批量新增")
    @PostMapping("/batchAdd")
    public Result<List<Customer>> batchAdd(
            @ApiParam(name = "customerList", value = "客户模型", required = true) @RequestBody List<Customer> customerList) {

        notNull(customerList, "输入参数不能为空");

        return ResultGenerator.genSuccessResult(customerRepository.saveAll(customerList));
    }

    /**
     * @create wanggx_ruiyi 2021-01-19 根据名字查找客户
     * @param firstName 名字
     * @return
     */
    @ApiOperation(value="根据名字查找客户",notes = "根据名字查找客户")
    @PostMapping("/findByFirstName")
    public Result<Customer> findByFirstName(
            @ApiParam(name = "firstName", value = "名字", required = true) @RequestParam String firstName) {

        notNull(firstName, "输入参数不能为空");

        return ResultGenerator.genSuccessResult(customerRepository.findByFirstName(firstName));
    }

    /**
     * @create wanggx_ruiyi 2021-01-19 根据姓氏查找客户
     * @param lastName 姓氏
     * @return
     */
    @ApiOperation(value="根据姓氏查找客户",notes = "根据姓氏查找客户")
    @PostMapping("/findByLastName")
    public Result<List<Customer>> findByLastName(
            @ApiParam(name = "lastName", value = "姓氏", required = true) @RequestParam String lastName) {

        notNull(lastName, "输入参数不能为空");

        return ResultGenerator.genSuccessResult(customerRepository.findByLastName(lastName));
    }

    /**
     * @create wanggx_ruiyi 2021-01-19 根据id查找客户
     * @param id 数据id
     * @return
     */
    @ApiOperation(value="根据id查找客户",notes = "根据id查找客户")
    @PostMapping("/findById")
    public Result<Customer> findById(
            @ApiParam(name = "id", value = "数据ID", required = true) @RequestParam String id) {

        notNull(id, "输入参数不能为空");

        Optional<Customer> customer = customerRepository.findById(id);
        return ResultGenerator.genSuccessResult(customer.isPresent() ? customer.get() : null);
    }

    /**
     * @create wanggx_ruiyi 2021-01-19 根据id判断客户是否存在
     * @param id 数据id
     * @return
     */
    @ApiOperation(value="根据id判断客户是否存在",notes = "根据id判断客户是否存在")
    @PostMapping("/existsById")
    public Result<Boolean> existsById(
            @ApiParam(name = "id", value = "数据ID", required = true) @RequestParam String id) {

        notNull(id, "输入参数不能为空");

        return ResultGenerator.genSuccessResult(customerRepository.existsById(id));
    }

    /**
     * @create wanggx_ruiyi 2021-01-19 查找所有客户
     * @return
     */
    @ApiOperation(value="查找所有客户",notes = "查找所有客户")
    @PostMapping("/findAll")
    public Result<List<Customer>> findAll() {

        return ResultGenerator.genSuccessResult(customerRepository.findAll());
    }

    /**
     * @create wanggx_ruiyi 2021-01-19 查找所有客户(排序)
     * @return
     */
    @ApiOperation(value="查找所有客户(排序)",notes = "查找所有客户(排序)")
    @PostMapping("/findAllBySort")
    public Result<List<Customer>> findAllBySort() {

        return ResultGenerator.genSuccessResult(customerRepository.findAll(Sort.by("id")));
    }

}

4.2 基于通用MyBatis Mapper插件的Service接口的实现

4.2.1 创建MongonService接口

import org.springframework.data.domain.Pageable;
import java.util.List;

/**
* MongonService 层 基础接口,其他有关mongo的Service 接口 请继承该接口
*/
public interface MongonService<T> {
/**
* 持久化
* @param model
*/
void save(T model);

/**
* 批量持久化
* @param models
*/
void save(List<T> models);

/**
* 通过_id刪除
* @param id
*/
void deleteById(String id);

/**
* 批量删除
* @param models
*/
void deleteAll(List<T> models);

/**
* 更新每个实体--需自己实现
* @param model
* @return
*/
int update(T model);

/**
* 通过ID查找
* @param id
* @return
*/
T findById(String id);

/**
* 获取所有
* @return
*/
List<T> findAll();

/**
* 通过分页查询
* @param pageable
* @return
*/
List<T> findByPage(Pageable pageable);
}

4.2.2 创建AbstractMongoService抽象类实现MongonService接口

import com.ruiyicloud.bbfbusiness.service.mongo.MongonService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;

import java.lang.reflect.ParameterizedType;
import java.util.List;

/**
 * 基于通用MyBatis Mapper插件的Service接口的实现
 */
public abstract class AbstractMongoService<T> implements MongonService<T> {

    /**
     * 由springboot自动注入,默认配置会产生mongoTemplate这个bean
     */
    @Autowired
    private MongoTemplate mongoTemplate;

    // 当前泛型真实类型的Class
    private Class<T> modelClass;

    public AbstractMongoService() {
        // 返回表示由该类对象表示的实体(类、接口、基元类型或void)的直接超类的类型
        ParameterizedType pt = (ParameterizedType) this.getClass().getGenericSuperclass();
        // 返回表示此类型的实际类型参数的类型对象数组。
        modelClass = (Class<T>) pt.getActualTypeArguments()[0];
    }

    /**
     * 插入一个集合
     */
    @Override
    public void save(List<T> models) {
        mongoTemplate.insertAll(models);
    }

    /**
     * 查找全部
     */
    @Override
    public List<T> findAll() {
        return mongoTemplate.findAll(modelClass);
    }

    /**
     * 根据id得到对象
     */
    @Override
    public T findById(String id) {
        return mongoTemplate.findById(id, modelClass);
//        return mongoTemplate.findOne(new Query(Criteria.where("_id").is(id)), modelClass);
    }

    /**
     * 插入
     */
    @Override
    public void save(T model) {
        mongoTemplate.insert(model);
    }

    /**
     * 根据id删除
     */
    @Override
    public void deleteById(String id) {
        T model = findById(id);
        mongoTemplate.remove(model);
//        Criteria criteria = Criteria.where("_id").is(id);
//        Query query = new Query(criteria);
//        mongoTemplate.remove(query,modelClass);
    }

    /**
     * 批量删除
     *
     * @param models
     */
    @Override
    public void deleteAll(List<T> models) {
        for (T model : models) {
            mongoTemplate.remove(model);
        }
    }

    /**
     * 分页查找
     * pageable代表分页bean
     */
    @Override
    public List<T> findByPage(Pageable pageable) {
        Query query = new Query();
        List<T> list = mongoTemplate.find(query.with(pageable), modelClass);
        return list;
    }
}

4.2.3 使用示例

// Service 示例代码
public interface EmrFileInfoService extends MongonService<EmrFileInfo>{}
// Service impl 示例代码 @Service public class EmrFileInfoServiceImpl extends AbstractMongoService<EmrFileInfo> implements EmrFileInfoService {}

五、总结

  总的来说,Spring Boot集成MongoDB非常简单。


程序员灯塔
转载请注明原文链接:关于MongoDB的简单理解(三)–Spring Boot篇
喜欢 (0)