当前位置: 首页 > ops >正文

Springboot+MongoDB简单使用示例

一、maven中添加依赖

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

二、配置文件中添加连接

spring:mongodb:host: 192.168.56.10port: 27017database: share #指定操作的数据库

三、创建mongodb文档对应的实体类

@Data
@Schema(description = "站点位置")
public class StationLocation
{@Schema(description = "id")@Idprivate String id;@Schema(description = "站点id")private Long stationId;@Schema(description = "经纬度")private GeoJsonPoint location;@Schema(description = "创建时间")private Date createTime;
}

四、操作MongoDB数据库

Springboot提供了5种操作MongoDB的方式,下面简单介绍下它们的使用方法:

4.1 MongoTemplate

特点

  • 是 Spring Data MongoDB 提供的核心模板类

  • 提供丰富的 CRUD 操作方法

  • 支持复杂的查询和聚合操作

  • 需要手动编写查询逻辑

示例代码:

查询:

import org.springframework.data.geo.Circle;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.Metrics;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.geo.GeoJsonPoint;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;  // 注入@Autowiredprivate MongoTemplate mongoTemplate;// 调用mongoTemplate,查询周边数据// 查询指定经纬度附近的站点
public List<StationLocation> nearbyStation(String latitude, String longitude) {//确定中心点,根据经纬度获取站点信息GeoJsonPoint point = new GeoJsonPoint(Double.parseDouble(longitude), Double.parseDouble(latitude));//设置查询半径,查询站点周边50公里范围的信息Distance distance = new Distance(50, Metrics.KILOMETERS);//画圆 确定查询范围Circle circle = new Circle(point, distance);//查询MongoDB数据库中站点信息Query query = new Query(Criteria.where("location").withinSphere(circle));List<StationLocation> stations = mongoTemplate.find(query, StationLocation.class);
}

4.2 MongoRepository

特点

  • 基于 JPA 风格的 Repository 接口

  • 支持方法名自动生成查询

  • 提供基本的 CRUD 操作

  • 可通过注解扩展自定义查询

  • 适合简单的 CRUD 操作

示例代码:

创建Repository的接口

//StationLocation为要查询的文档对应的实体类,String为实体类StationLocation主键的类型
public interface StationLocationRepository extends MongoRepository<StationLocation, String> {//方法要规范命名,mongodb才能按图索骥找到对应的数据StationLocation getByStationId(Long id);}

调用上面定义的Repository新增插入数据:

 @Autowiredprivate StationLocationRepository stationLocationRepository;public int saveStation(Station station) {String provinceName = regionService.getNameByCode(station.getProvinceCode());String cityName = regionService.getNameByCode(station.getCityCode());String districtName = regionService.getNameByCode(station.getDistrictCode());station.setFullAddress(provinceName + cityName + districtName + station.getAddress());int rows = stationMapper.insert(station);StationLocation stationLocation = new StationLocation();stationLocation.setId(ObjectId.get().toString());stationLocation.setStationId(station.getId());stationLocation.setLocation(new GeoJsonPoint(station.getLongitude().doubleValue(), station.getLatitude().doubleValue()));stationLocation.setCreateTime(new Date());stationLocationRepository.save(stationLocation);return rows;}

修改数据

@Autowired
private StationLocationRepository stationLocationRepository;public int updateStation(Station station) {StationLocation stationLocation = stationLocationRepository.getByStationId(station.getId());stationLocation.setLocation(new GeoJsonPoint(station.getLongitude().doubleValue(), station.getLatitude().doubleValue()));stationLocationRepository.save(stationLocation);return rows;
}

4.3  ReactiveMongoTemplate

特点

  • 响应式编程模型的 MongoTemplate

  • 返回 Mono 或 Flux 类型

  • 适合非阻塞、异步应用

  • 需要 Spring WebFlux 环境

示例代码

@Autowired
private ReactiveMongoTemplate reactiveMongoTemplate;public Mono<User> findUserById(String id) {return reactiveMongoTemplate.findById(id, User.class);
}

4.4 ReactiveMongoRepository

特点

  • 响应式版本的 MongoRepository

  • 返回 Publisher 类型 (Mono/Flux)

  • 支持响应式流处理

  • 适合全栈响应式应用

示例代码

// 创建ReactiveRepository
public interface UserReactiveRepository extends ReactiveMongoRepository<User, String> {Flux<User> findByName(String name);
}// 使用
@Autowired
private UserReactiveRepository userReactiveRepository;

4.5  原生 MongoDB Java 驱动

特点

  • 直接使用 MongoDB 官方 Java 驱动

  • 不依赖 Spring Data 抽象层

  • 最灵活但也最底层

  • 需要手动处理更多细节

示例代码

@Autowired
private MongoClient mongoClient;public void insertUser(User user) {MongoDatabase database = mongoClient.getDatabase("test");MongoCollection<Document> collection = database.getCollection("users");collection.insertOne(new Document("name", user.getName()).append("age", user.getAge()));
}

五、主要区别对比

方式编程模型抽象级别适用场景学习曲线
MongoTemplate命令式中等复杂查询/操作中等
MongoRepository命令式简单 CRUD
ReactiveMongoTemplate响应式中等响应式复杂操作较高
ReactiveMongoRepository响应式响应式简单 CRUD中等
原生驱动命令式需要直接控制

六、选择建议

  1. 简单 CRUD:优先考虑 MongoRepository/ReactiveMongoRepository

  2. 复杂查询/聚合:使用 MongoTemplate/ReactiveMongoTemplate

  3. 响应式应用:选择 Reactive 版本

  4. 需要直接控制底层:使用原生驱动。

http://www.xdnf.cn/news/16295.html

相关文章:

  • 哈希指针与数据结构:构建可信数字世界的基石
  • window上建立git远程仓库
  • Android 键盘
  • GCN模型的设计与训练(入门案例)
  • Rust Web框架性能对比与实战指南
  • 计算机结构-逻辑门、存储器、内存、加法器、锁存器、程序计数器
  • Aerospike与Redis深度对比:从架构到性能的全方位解析
  • npm ERR! cb() never called!
  • sssss
  • Ubuntu安装node-red
  • 刷题日记0726
  • 杰理蓝牙耳机开发--三轴加速度传感器与IIC通信
  • 关于树(按序遍历,搜索,LCA)
  • Git版本控制
  • Linux 系统调用详解:操作文件的常用系统调用
  • 大语言模型 LLM 通过 Excel 知识库 增强日志分析,根因分析能力的技术方案(3):使用云平台最小外部依赖方案
  • Spring AI 项目实战(二十):基于Spring Boot + AI + DeepSeek的智能环境监测与分析平台(附完整源码)
  • GRE及MGRE应用综合实验
  • Day32| 509. 斐波那契数、70. 爬楼梯、746. 使用最小花费爬楼梯
  • 复杂产品系统集成协同研发平台的研究与实现
  • 【MySQL】MySQL 缓存方案
  • haproxy原理及实战部署
  • Vue3组件通信方法清单
  • CPU 为什么需要缓存?揭开速度与效率的底层逻辑
  • ICMPv6报文类型详解表
  • 如何检查服务器数据盘是否挂载成功?
  • 【Spring AI】大模型服务平台-阿里云百炼
  • 创建 Vue 项目的 4 种主流方式
  • Spark-TTS 使用
  • Caffeine 缓存库的常用功能使用介绍