Springboot+MongoDB的五種操作方式
一、maven中添加依賴
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-mongodb</artifactId> </dependency>
二、配置文件中添加連接
spring:
mongodb:
host: 192.168.56.10
port: 27017
database: share #指定操作的數(shù)據(jù)庫三、創(chuàng)建mongodb文檔對應的實體類
@Data
@Schema(description = "站點位置")
public class StationLocation
{
@Schema(description = "id")
@Id
private String id;
@Schema(description = "站點id")
private Long stationId;
@Schema(description = "經(jīng)緯度")
private GeoJsonPoint location;
@Schema(description = "創(chuàng)建時間")
private Date createTime;
}四、操作MongoDB數(shù)據(jù)庫
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;
// 注入
@Autowired
private MongoTemplate mongoTemplate;
// 調(diào)用mongoTemplate,查詢周邊數(shù)據(jù)
// 查詢指定經(jīng)緯度附近的站點
public List<StationLocation> nearbyStation(String latitude, String longitude) {
//確定中心點,根據(jù)經(jīng)緯度獲取站點信息
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數(shù)據(jù)庫中站點信息
Query query = new Query(Criteria.where("location").withinSphere(circle));
List<StationLocation> stations = mongoTemplate.find(query, StationLocation.class);
}
4.2 MongoRepository
特點:
- 基于 JPA 風格的 Repository 接口
- 支持方法名自動生成查詢
- 提供基本的 CRUD 操作
- 可通過注解擴展自定義查詢
- 適合簡單的 CRUD 操作
示例代碼:
創(chuàng)建Repository的接口
//StationLocation為要查詢的文檔對應的實體類,String為實體類StationLocation主鍵的類型
public interface StationLocationRepository extends MongoRepository<StationLocation, String> {
//方法要規(guī)范命名,mongodb才能按圖索驥找到對應的數(shù)據(jù)
StationLocation getByStationId(Long id);
}調(diào)用上面定義的Repository新增插入數(shù)據(jù):
@Autowired
private 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;
}修改數(shù)據(jù)
@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 環(huán)境
示例代碼:
@Autowired
private ReactiveMongoTemplate reactiveMongoTemplate;
public Mono<User> findUserById(String id) {
return reactiveMongoTemplate.findById(id, User.class);
}4.4 ReactiveMongoRepository
特點:
- 響應式版本的 MongoRepository
- 返回 Publisher 類型 (Mono/Flux)
- 支持響應式流處理
- 適合全棧響應式應用
示例代碼:
// 創(chuàng)建ReactiveRepository
public interface UserReactiveRepository extends ReactiveMongoRepository<User, String> {
Flux<User> findByName(String name);
}
// 使用
@Autowired
private UserReactiveRepository userReactiveRepository;4.5 原生 MongoDB Java 驅(qū)動
特點:
- 直接使用 MongoDB 官方 Java 驅(qū)動
- 不依賴 Spring Data 抽象層
- 最靈活但也最底層
- 需要手動處理更多細節(jié)
示例代碼:
@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()));
}五、主要區(qū)別對比
| 方式 | 編程模型 | 抽象級別 | 適用場景 | 學習曲線 |
|---|---|---|---|---|
| MongoTemplate | 命令式 | 中等 | 復雜查詢/操作 | 中等 |
| MongoRepository | 命令式 | 高 | 簡單 CRUD | 低 |
| ReactiveMongoTemplate | 響應式 | 中等 | 響應式復雜操作 | 較高 |
| ReactiveMongoRepository | 響應式 | 高 | 響應式簡單 CRUD | 中等 |
| 原生驅(qū)動 | 命令式 | 低 | 需要直接控制 | 高 |
六、選擇建議
- 簡單 CRUD:優(yōu)先考慮 MongoRepository/ReactiveMongoRepository
- 復雜查詢/聚合:使用 MongoTemplate/ReactiveMongoTemplate
- 響應式應用:選擇 Reactive 版本
- 需要直接控制底層:使用原生驅(qū)動。
到此這篇關(guān)于Springboot+MongoDB簡單使用示例的文章就介紹到這了,更多相關(guān)Springboot MongoDB使用內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
教你Java中的Lock鎖底層AQS到底是如何實現(xiàn)的
本文是基于ReentrantLock來講解,ReentrantLock加鎖只是對AQS的api的調(diào)用,底層的鎖的狀態(tài)(state)和其他線程等待(Node雙向鏈表)的過程其實是由AQS來維護的,對Java?Lock鎖AQS實現(xiàn)過程感興趣的朋友一起看看吧2022-05-05
Spring SpringMVC在啟動完成后執(zhí)行方法源碼解析
這篇文章主要介紹了SpringMVC在啟動完成后執(zhí)行方法源碼解析,還是非常不錯的,在這里分享給大家,需要的朋友可以參考下。2017-09-09
springmvc fastjson 反序列化時間格式化方法(推薦)
下面小編就為大家?guī)硪黄猻pringmvc fastjson 反序列化時間格式化方法(推薦)。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-04-04
使用HandlerMethodArgumentResolver用于統(tǒng)一獲取當前登錄用戶
這篇文章主要介紹了使用HandlerMethodArgumentResolver用于統(tǒng)一獲取當前登錄用戶實例,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-12-12
多jdk環(huán)境下指定springboot外部配置文件詳解
這篇文章主要為大家介紹了多jdk環(huán)境下指定springboot外部配置文件詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-03-03

