Bootstrap

【JAVA】SpringBoot + mongodb 分页、排序、动态多条件查询及事务处理

【JAVA】SpringBoot + mongodb 分页、排序、动态多条件查询及事务处理

1.引入依赖

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

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

2.配置application.yml

spring:
  data:
    # mongodb多数据源配置
    mongodb:
      host: 192.168.36.238
      port: 27017
      username: yapi
      password: Qsxdcfr2313!
      database: yapi
      # 验证数据库
      authentication-database: admin
      # 第二个数据库
      low-code:
        uri: mongodb://yapi:Qsxdcfr2313[email protected]:27017/low-code?authSource=admin
      # 第三个数据库
      event:
        uri: mongodb://yapi:Qsxdcfr2313[email protected]:27017/event?authSource=admin

3.MongoDB多数据源配置

创建MongoConfig类

package com.xhs.config;

import com.mongodb.client.MongoClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.mongo.MongoProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoClientDatabaseFactory;

import javax.annotation.Resource;

/**
 * @desc: MongoDB多数据源配置
 * @projectName: spring-boot-demo
 * @author: xhs
 * @date: 2023-11-23 16:06:22
 * @version: JDK 1.8
 */

@Configuration
public class MongoConfig {

    @Resource
    private MongoClient mongoClient;

    @Resource
    private MongoProperties mongoProperties;

    /**
     * 默认的数据库
     *
     * @return MongoTemplate
     */
    @Bean
    public MongoTemplate mongoTemplate() {
        return new MongoTemplate(mongoClient, mongoProperties.getDatabase());
    }

    /**
     * 第二个数据源
     *
     * @param adminUri uri
     * @return MongoTemplate
     */
    @Bean
    public MongoTemplate mongoTemplateLowCode(@Value("${spring.data.mongodb.low-code.uri}") String adminUri) {
        return new MongoTemplate(new SimpleMongoClientDatabaseFactory(adminUri));
    }

    /**
     * 第三个数据源
     *
     * @param adminUri uri
     * @return MongoTemplate
     */
    @Bean
    public MongoTemplate mongoTemplateEvent(@Value("${spring.data.mongodb.event.uri}") String adminUri) {
        return new MongoTemplate(new SimpleMongoClientDatabaseFactory(adminUri));
    }
}

4.创建实体类

创建三个库的实体类

第一库的实体类

package com.xhs.entity.mongo;

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

/**
 * @desc: yapi库的user集合
 * @projectName: spring-boot-demo
 * @author: xhs
 * @date: 2023-11-23 023 16:14
 * @version: JDK 1.8
 */
@Data
@Document(collection = "user")
public class User {

    @Id
    private String id;

    /**
     * 用户名
     */
    private String username;

    /**
     * 角色
     */
    private String role;
}

第二个库的实体类

package com.xhs.entity.mongo;

import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;

import java.util.Date;

/**
 * @desc: low-code库的low_code_url集合
 * @projectName: spring-boot-demo
 * @author: xhs
 * @date: 2023-11-23 023 16:10
 * @version: JDK 1.8
 */
@Data
@Document(collection = "low_code_url")
public class LowCodeUrl {

    @Id
    private String id;

    /**
     * 系统类型
     */
    private String systemName;

    /**
     * 对象名称
     */
    private String objectName;

    /**
     * 接口地址
     */
    private String interfaceUrl;

    /**
     * 接口类型
     */
    private String interfaceType;

    /**
     * 创建时间
     */
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private Date createTime;

    /**
     * 更新时间
     */
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private Date updateTime;
}

第三个库的实体类

package com.xhs.entity.mongo;

import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;

import java.util.Date;

/**
 * @desc: event库的event集合
 * @projectName: spring-boot-demo
 * @author: xhs
 * @date: 2023-11-23 023 16:17
 * @version: JDK 1.8
 */
@Data
@Document(collection = "event")
public class Event {

    @Id
    private String id;

    /**
     * 事件名称
     */
    private String eventName;

    /**
     * 事件类型
     */
    private String eventType;

    /**
     * 触发方式
     */
    private String triggerMode;

    /**
     * 创建时间
     */
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private Date createTime;

    /**
     * 更新时间
     */
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private Date updateTime;
}

5.创建Controller层

package com.xhs.controller;

import com.xhs.dto.request.AddEventParams;
import com.xhs.dto.request.AddLowCodeUrlParams;
import com.xhs.dto.request.FindLowCodeUrlParams;
import com.xhs.dto.request.PageEventParams;
import com.xhs.message.ReturnResult;
import com.xhs.service.MongoService;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * @desc:
 * @projectName: spring-boot-demo
 * @author: xhs
 * @date: 2023-11-23 023 16:19
 * @version: JDK 1.8
 */
@RestController
@RequestMapping("/mongo")
public class MongoController {

    @Resource
    private MongoService mongoService;

    /**
     * 查询所有用户
     *
     * @return ReturnResult<Object>
     */
    @GetMapping("/getUser")
    public ReturnResult<Object> getUser() {
        return mongoService.getUser();
    }

    /**
     * 条件查询 LowCodeUrl
     *
     * @param findLowCodeUrlParams 查询条件
     * @return ReturnResult<Object>
     */
    @PostMapping("/getLowCodeUrl")
    public ReturnResult<Object> getLowCodeUrl(@RequestBody FindLowCodeUrlParams findLowCodeUrlParams) {
        return mongoService.getLowCodeUrl(findLowCodeUrlParams);
    }

    /**
     * 新增 LowCodeUrl 数据
     *
     * @param lowCodeUrlParams LowCodeUrl 数据
     * @return ReturnResult<Object>
     */
    @PostMapping("/addLowCodeUrl")
    public ReturnResult<Object> addLowCodeUrl(@Validated @RequestBody AddLowCodeUrlParams lowCodeUrlParams) {
        return mongoService.addLowCodeUrl(lowCodeUrlParams);
    }

    /**
     * 新增 event 数据
     *
     * @param eventParams LowCodeUrl 数据
     * @return ReturnResult<Object>
     */
    @PostMapping("/addEvent")
    public ReturnResult<Object> addEvent(@Validated @RequestBody AddEventParams eventParams) {
        return mongoService.addEvent(eventParams);
    }

    /**
     * 分页查询 event 数据
     *
     * @param eventParams 查询条件
     * @return ReturnResult<Object>
     */
    @PostMapping("/pageEvent")
    public ReturnResult<Object> pageEvent(@Validated @RequestBody PageEventParams eventParams) {
        return mongoService.pageEvent(eventParams);
    }
}

6.创建Service层

package com.xhs.service;

import com.xhs.dto.request.AddEventParams;
import com.xhs.dto.request.AddLowCodeUrlParams;
import com.xhs.dto.request.FindLowCodeUrlParams;
import com.xhs.dto.request.PageEventParams;
import com.xhs.message.ReturnResult;

/**
 * @desc:
 * @projectName: spring-boot-demo
 * @author: xhs
 * @date: 2023-11-23 023 16:20
 * @version: JDK 1.8
 */
public interface MongoService {

    /**
     * 查询所有用户
     *
     * @return ReturnResult<Object>
     */
    ReturnResult<Object> getUser();

    /**
     * 条件查询 LowCodeUrl
     *
     * @param findLowCodeUrlParams 查询条件
     * @return ReturnResult<Object>
     */
    ReturnResult<Object> getLowCodeUrl(FindLowCodeUrlParams findLowCodeUrlParams);

    /**
     * 新增 LowCodeUrl 数据
     *
     * @param lowCodeUrlParams LowCodeUrl 数据
     * @return ReturnResult<Object>
     */
    ReturnResult<Object> addLowCodeUrl(AddLowCodeUrlParams lowCodeUrlParams);


    /**
     * 新增 event 数据
     *
     * @param eventParams LowCodeUrl 数据
     * @return ReturnResult<Object>
     */
    ReturnResult<Object> addEvent(AddEventParams eventParams);

    /**
     * 分页查询 event 数据
     *
     * @param eventParams 查询条件
     * @return ReturnResult<Object>
     */
    ReturnResult<Object> pageEvent(PageEventParams eventParams);
}

7.创建ServiceImpl层

package com.xhs.service.impl;

import com.xhs.dto.request.AddEventParams;
import com.xhs.dto.request.AddLowCodeUrlParams;
import com.xhs.dto.request.FindLowCodeUrlParams;
import com.xhs.dto.request.PageEventParams;
import com.xhs.dto.response.PageResult;
import com.xhs.entity.mongo.Event;
import com.xhs.entity.mongo.LowCodeUrl;
import com.xhs.entity.mongo.User;
import com.xhs.message.Result;
import com.xhs.message.ReturnResult;
import com.xhs.service.MongoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
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.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

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

/**
 * @desc:
 * @projectName: spring-boot-demo
 * @author: xhs
 * @date: 2023-11-23 023 16:20
 * @version: JDK 1.8
 */
@Slf4j
@Service
public class MongoServiceImpl implements MongoService {

    @Resource
    @Qualifier("mongoTemplate")
    private MongoTemplate mongoTemplate;

    @Resource
    @Qualifier("mongoTemplateLowCode")
    private MongoTemplate mongoTemplateLowCode;

    @Resource
    @Qualifier("mongoTemplateEvent")
    private MongoTemplate mongoTemplateEvent;


    /**
     * 查询所有用户
     *
     * @return ReturnResult<Object>
     */
    @Override
    public ReturnResult<Object> getUser() {
        List<User> users = mongoTemplate.find(new Query(), User.class);
        return ReturnResult.build(Result.QUERY_SUCCESS).setData(users);
    }

    /**
     * 条件查询 LowCodeUrl
     *
     * @param findLowCodeUrlParams 查询条件
     * @return ReturnResult<Object>
     */
    @Override
    public ReturnResult<Object> getLowCodeUrl(FindLowCodeUrlParams findLowCodeUrlParams) {
        Query query = new Query();
        if (StringUtils.hasLength(findLowCodeUrlParams.getSystemName())) {
            // regex 模糊查询
            query.addCriteria(Criteria.where("systemName").regex(findLowCodeUrlParams.getSystemName()));
        }
        if (StringUtils.hasLength(findLowCodeUrlParams.getObjectName())) {
            // regex 模糊查询
            query.addCriteria(Criteria.where("objectName").regex(findLowCodeUrlParams.getObjectName()));
        }
        if (StringUtils.hasLength(findLowCodeUrlParams.getInterfaceType())) {
            query.addCriteria(Criteria.where("interfaceType").is(findLowCodeUrlParams.getInterfaceType()));
        }
        List<LowCodeUrl> lowCodeUrlList = mongoTemplateLowCode.find(query, LowCodeUrl.class);
        return ReturnResult.build(Result.QUERY_SUCCESS).setData(lowCodeUrlList);
    }

    /**
     * 新增 LowCodeUrl 数据
     *
     * @param lowCodeUrlParams LowCodeUrl 数据
     * @return ReturnResult<Object>
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ReturnResult<Object> addLowCodeUrl(AddLowCodeUrlParams lowCodeUrlParams) {
        Date date = new Date();
        LowCodeUrl codeUrl = new LowCodeUrl();
        codeUrl.setSystemName(lowCodeUrlParams.getSystemName());
        codeUrl.setObjectName(lowCodeUrlParams.getObjectName());
        codeUrl.setInterfaceUrl(lowCodeUrlParams.getInterfaceUrl());
        codeUrl.setInterfaceType(lowCodeUrlParams.getInterfaceType());
        codeUrl.setCreateTime(date);
        codeUrl.setUpdateTime(date);
        LowCodeUrl insert = mongoTemplateLowCode.insert(codeUrl);
        return ReturnResult.build(Result.ADD_SUCCESS).setData(insert.getId());
    }

    /**
     * 新增 event 数据
     *
     * @param eventParams LowCodeUrl 数据
     * @return ReturnResult<Object>
     */
    @Override
    public ReturnResult<Object> addEvent(AddEventParams eventParams) {
        Date date = new Date();
        Event event = new Event();
        event.setEventName(eventParams.getEventName());
        event.setEventType(eventParams.getEventType());
        event.setTriggerMode(eventParams.getTriggerMode());
        event.setCreateTime(date);
        event.setUpdateTime(date);
        Event insert = mongoTemplateEvent.insert(event);
        return ReturnResult.build(Result.ADD_SUCCESS).setData(insert.getId());
    }

    /**
     * 分页查询 event 数据
     *
     * @param eventParams 查询条件
     * @return ReturnResult<Object>
     */
    @Override
    public ReturnResult<Object> pageEvent(PageEventParams eventParams) {
        // 排序字段
        Sort sort = Sort.by(Sort.Direction.DESC, "createTime");
        // 分页,PageNumber()-1是因为第一页的下标为0 ,入参PageNumber最小值为1
        Pageable pageRequest = PageRequest.of(eventParams.getPageNumber()-1, eventParams.getPageSize(), sort);
        // 查询条件
        Query query = new Query();
        if (StringUtils.hasLength(eventParams.getEventName())) {
            // regex 模糊查询
            query.addCriteria(Criteria.where("eventName").regex(eventParams.getEventName()));
        }
        if (StringUtils.hasLength(eventParams.getEventType())) {
            // regex 模糊查询
            query.addCriteria(Criteria.where("eventType").regex(eventParams.getEventType()));
        }
        if (StringUtils.hasLength(eventParams.getTriggerMode())) {
            // regex 模糊查询
            query.addCriteria(Criteria.where("triggerMode").regex(eventParams.getTriggerMode()));
        }
        query.with(pageRequest);
        // 查询总数
        long count = mongoTemplateEvent.count(query, Event.class);
        // 查询数据
        List<Event> events = mongoTemplateEvent.find(query, Event.class);
        // 分页结果
        PageResult<List<Event>> result = new PageResult<>();
        result.setPageNumber(eventParams.getPageNumber());
        result.setPageSize(eventParams.getPageSize());
        result.setTotalRow(count);
        result.setRecords(events);
        return ReturnResult.build(Result.QUERY_SUCCESS).setData(result);
    }
}

8.源码地址

https://gitee.com/xhs101/spring-boot-mongodb.git

9.查询效果:

在这里插入图片描述

在这里插入图片描述

;