【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:27017username: yapi
password: Qsxdcfr2313!database: yapi
# 验证数据库authentication-database: admin
# 第二个数据库low-code:uri: mongodb://yapi:[email protected]:27017/low-code?authSource=admin# 第三个数据库event:uri: mongodb://yapi:[email protected]:27017/event?authSource=admin
3.MongoDB多数据源配置
创建MongoConfig类
packagecom.xhs.config;importcom.mongodb.client.MongoClient;importorg.springframework.beans.factory.annotation.Value;importorg.springframework.boot.autoconfigure.mongo.MongoProperties;importorg.springframework.context.annotation.Bean;importorg.springframework.context.annotation.Configuration;importorg.springframework.data.mongodb.core.MongoTemplate;importorg.springframework.data.mongodb.core.SimpleMongoClientDatabaseFactory;importjavax.annotation.Resource;/**
* @desc: MongoDB多数据源配置
* @projectName: spring-boot-demo
* @author: xhs
* @date: 2023-11-23 16:06:22
* @version: JDK 1.8
*/@ConfigurationpublicclassMongoConfig{@ResourceprivateMongoClient mongoClient;@ResourceprivateMongoProperties mongoProperties;/**
* 默认的数据库
*
* @return MongoTemplate
*/@BeanpublicMongoTemplatemongoTemplate(){returnnewMongoTemplate(mongoClient, mongoProperties.getDatabase());}/**
* 第二个数据源
*
* @param adminUri uri
* @return MongoTemplate
*/@BeanpublicMongoTemplatemongoTemplateLowCode(@Value("${spring.data.mongodb.low-code.uri}")String adminUri){returnnewMongoTemplate(newSimpleMongoClientDatabaseFactory(adminUri));}/**
* 第三个数据源
*
* @param adminUri uri
* @return MongoTemplate
*/@BeanpublicMongoTemplatemongoTemplateEvent(@Value("${spring.data.mongodb.event.uri}")String adminUri){returnnewMongoTemplate(newSimpleMongoClientDatabaseFactory(adminUri));}}
4.创建实体类
创建三个库的实体类
第一库的实体类
packagecom.xhs.entity.mongo;importlombok.Data;importorg.springframework.data.annotation.Id;importorg.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")publicclassUser{@IdprivateString id;/**
* 用户名
*/privateString username;/**
* 角色
*/privateString role;}
第二个库的实体类
packagecom.xhs.entity.mongo;importcom.fasterxml.jackson.annotation.JsonFormat;importlombok.Data;importorg.springframework.data.annotation.Id;importorg.springframework.data.mongodb.core.mapping.Document;importjava.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")publicclassLowCodeUrl{@IdprivateString id;/**
* 系统类型
*/privateString systemName;/**
* 对象名称
*/privateString objectName;/**
* 接口地址
*/privateString interfaceUrl;/**
* 接口类型
*/privateString interfaceType;/**
* 创建时间
*/@JsonFormat(pattern ="yyyy-MM-dd HH:mm:ss")privateDate createTime;/**
* 更新时间
*/@JsonFormat(pattern ="yyyy-MM-dd HH:mm:ss")privateDate updateTime;}
第三个库的实体类
packagecom.xhs.entity.mongo;importcom.fasterxml.jackson.annotation.JsonFormat;importlombok.Data;importorg.springframework.data.annotation.Id;importorg.springframework.data.mongodb.core.mapping.Document;importjava.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")publicclassEvent{@IdprivateString id;/**
* 事件名称
*/privateString eventName;/**
* 事件类型
*/privateString eventType;/**
* 触发方式
*/privateString triggerMode;/**
* 创建时间
*/@JsonFormat(pattern ="yyyy-MM-dd HH:mm:ss")privateDate createTime;/**
* 更新时间
*/@JsonFormat(pattern ="yyyy-MM-dd HH:mm:ss")privateDate updateTime;}
5.创建Controller层
packagecom.xhs.controller;importcom.xhs.dto.request.AddEventParams;importcom.xhs.dto.request.AddLowCodeUrlParams;importcom.xhs.dto.request.FindLowCodeUrlParams;importcom.xhs.dto.request.PageEventParams;importcom.xhs.message.ReturnResult;importcom.xhs.service.MongoService;importorg.springframework.validation.annotation.Validated;importorg.springframework.web.bind.annotation.*;importjavax.annotation.Resource;/**
* @desc:
* @projectName: spring-boot-demo
* @author: xhs
* @date: 2023-11-23 023 16:19
* @version: JDK 1.8
*/@RestController@RequestMapping("/mongo")publicclassMongoController{@ResourceprivateMongoService mongoService;/**
* 查询所有用户
*
* @return ReturnResult<Object>
*/@GetMapping("/getUser")publicReturnResult<Object>getUser(){return mongoService.getUser();}/**
* 条件查询 LowCodeUrl
*
* @param findLowCodeUrlParams 查询条件
* @return ReturnResult<Object>
*/@PostMapping("/getLowCodeUrl")publicReturnResult<Object>getLowCodeUrl(@RequestBodyFindLowCodeUrlParams findLowCodeUrlParams){return mongoService.getLowCodeUrl(findLowCodeUrlParams);}/**
* 新增 LowCodeUrl 数据
*
* @param lowCodeUrlParams LowCodeUrl 数据
* @return ReturnResult<Object>
*/@PostMapping("/addLowCodeUrl")publicReturnResult<Object>addLowCodeUrl(@Validated@RequestBodyAddLowCodeUrlParams lowCodeUrlParams){return mongoService.addLowCodeUrl(lowCodeUrlParams);}/**
* 新增 event 数据
*
* @param eventParams LowCodeUrl 数据
* @return ReturnResult<Object>
*/@PostMapping("/addEvent")publicReturnResult<Object>addEvent(@Validated@RequestBodyAddEventParams eventParams){return mongoService.addEvent(eventParams);}/**
* 分页查询 event 数据
*
* @param eventParams 查询条件
* @return ReturnResult<Object>
*/@PostMapping("/pageEvent")publicReturnResult<Object>pageEvent(@Validated@RequestBodyPageEventParams eventParams){return mongoService.pageEvent(eventParams);}}
6.创建Service层
packagecom.xhs.service;importcom.xhs.dto.request.AddEventParams;importcom.xhs.dto.request.AddLowCodeUrlParams;importcom.xhs.dto.request.FindLowCodeUrlParams;importcom.xhs.dto.request.PageEventParams;importcom.xhs.message.ReturnResult;/**
* @desc:
* @projectName: spring-boot-demo
* @author: xhs
* @date: 2023-11-23 023 16:20
* @version: JDK 1.8
*/publicinterfaceMongoService{/**
* 查询所有用户
*
* @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层
packagecom.xhs.service.impl;importcom.xhs.dto.request.AddEventParams;importcom.xhs.dto.request.AddLowCodeUrlParams;importcom.xhs.dto.request.FindLowCodeUrlParams;importcom.xhs.dto.request.PageEventParams;importcom.xhs.dto.response.PageResult;importcom.xhs.entity.mongo.Event;importcom.xhs.entity.mongo.LowCodeUrl;importcom.xhs.entity.mongo.User;importcom.xhs.message.Result;importcom.xhs.message.ReturnResult;importcom.xhs.service.MongoService;importlombok.extern.slf4j.Slf4j;importorg.springframework.beans.factory.annotation.Qualifier;importorg.springframework.data.domain.PageRequest;importorg.springframework.data.domain.Pageable;importorg.springframework.data.domain.Sort;importorg.springframework.data.mongodb.core.MongoTemplate;importorg.springframework.data.mongodb.core.query.Criteria;importorg.springframework.data.mongodb.core.query.Query;importorg.springframework.stereotype.Service;importorg.springframework.transaction.annotation.Transactional;importorg.springframework.util.StringUtils;importjavax.annotation.Resource;importjava.util.Date;importjava.util.List;/**
* @desc:
* @projectName: spring-boot-demo
* @author: xhs
* @date: 2023-11-23 023 16:20
* @version: JDK 1.8
*/@Slf4j@ServicepublicclassMongoServiceImplimplementsMongoService{@Resource@Qualifier("mongoTemplate")privateMongoTemplate mongoTemplate;@Resource@Qualifier("mongoTemplateLowCode")privateMongoTemplate mongoTemplateLowCode;@Resource@Qualifier("mongoTemplateEvent")privateMongoTemplate mongoTemplateEvent;/**
* 查询所有用户
*
* @return ReturnResult<Object>
*/@OverridepublicReturnResult<Object>getUser(){List<User> users = mongoTemplate.find(newQuery(),User.class);returnReturnResult.build(Result.QUERY_SUCCESS).setData(users);}/**
* 条件查询 LowCodeUrl
*
* @param findLowCodeUrlParams 查询条件
* @return ReturnResult<Object>
*/@OverridepublicReturnResult<Object>getLowCodeUrl(FindLowCodeUrlParams findLowCodeUrlParams){Query query =newQuery();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);returnReturnResult.build(Result.QUERY_SUCCESS).setData(lowCodeUrlList);}/**
* 新增 LowCodeUrl 数据
*
* @param lowCodeUrlParams LowCodeUrl 数据
* @return ReturnResult<Object>
*/@Override@Transactional(rollbackFor =Exception.class)publicReturnResult<Object>addLowCodeUrl(AddLowCodeUrlParams lowCodeUrlParams){Date date =newDate();LowCodeUrl codeUrl =newLowCodeUrl();
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);returnReturnResult.build(Result.ADD_SUCCESS).setData(insert.getId());}/**
* 新增 event 数据
*
* @param eventParams LowCodeUrl 数据
* @return ReturnResult<Object>
*/@OverridepublicReturnResult<Object>addEvent(AddEventParams eventParams){Date date =newDate();Event event =newEvent();
event.setEventName(eventParams.getEventName());
event.setEventType(eventParams.getEventType());
event.setTriggerMode(eventParams.getTriggerMode());
event.setCreateTime(date);
event.setUpdateTime(date);Event insert = mongoTemplateEvent.insert(event);returnReturnResult.build(Result.ADD_SUCCESS).setData(insert.getId());}/**
* 分页查询 event 数据
*
* @param eventParams 查询条件
* @return ReturnResult<Object>
*/@OverridepublicReturnResult<Object>pageEvent(PageEventParams eventParams){// 排序字段Sort sort =Sort.by(Sort.Direction.DESC,"createTime");// 分页,PageNumber()-1是因为第一页的下标为0 ,入参PageNumber最小值为1Pageable pageRequest =PageRequest.of(eventParams.getPageNumber()-1, eventParams.getPageSize(), sort);// 查询条件Query query =newQuery();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 =newPageResult<>();
result.setPageNumber(eventParams.getPageNumber());
result.setPageSize(eventParams.getPageSize());
result.setTotalRow(count);
result.setRecords(events);returnReturnResult.build(Result.QUERY_SUCCESS).setData(result);}}
8.源码地址
https://gitee.com/xhs101/spring-boot-mongodb.git
9.查询效果:
本文转载自: https://blog.csdn.net/qq_42021376/article/details/134601752
版权归原作者 TOP灬小朋友 所有, 如有侵权,请联系我们删除。
版权归原作者 TOP灬小朋友 所有, 如有侵权,请联系我们删除。