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

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.dtcms.com/a/299515.html

相关文章:

  • Java 大视界 -- Java 大数据在智能安防视频监控系统中的视频语义理解与智能检索进阶(365)
  • MySQL 中 VARCHAR(50) 和 VARCHAR(500) 的区别
  • Python训练Day24
  • 机器学习入门:线性回归详解与实战
  • Javaweb————HTTP的九种请求方法介绍
  • VTK交互——CallData
  • MySQL操作进阶
  • setsockopt函数概念和使用案例
  • python---字典(dict)
  • 瑞吉外卖学习笔记
  • 基于FPGA的SPI控制FLASH读写
  • 【C++高效编程】STL queue深度剖析:从底层原理到高级应用
  • 什么是ICMP报文?有什么用?
  • 以实时语音转文字项目为例,介绍一下如何手动部署python应用到Linux服务器(附脚本)
  • 根据ip获取地址库
  • 【Git】Git下载全攻略:从入门到精通
  • 如何在 Git 中控制某些文件不被提交?
  • 图解网络-小林coding笔记(持续更新)
  • 【2025最新】浏览器插件开发选型建议:WXT、Plasmo、原生TS/JS
  • 融合为体,AI为用:数据库在智能时代的破局之道
  • Maven之依赖管理
  • 《Java 程序设计》第 6 章 - 字符串
  • 智慧城市多目标追踪精度↑32%:陌讯动态融合算法实战解析
  • 【Canvas与旗帜】条纹版大明三辰旗
  • 神经网络中的反向传播原理:驱动智能的核心引擎
  • k8s:将打包好的 Kubernetes 集群镜像推送到Harbor私有镜像仓库
  • 电子电气架构 --- 高阶智能驾驶对E/E架构的新要求
  • Java操作Excel文档
  • Spring的深入浅出(6)--使用AOP的思想改造转账案例
  • 人形机器人指南(八)操作