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文檔對應(yīng)的實(shí)體類
@Data @Schema(description = "站點(diǎn)位置") public class StationLocation { @Schema(description = "id") @Id private String id; @Schema(description = "站點(diǎn)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
特點(diǎn):
- 是 Spring Data MongoDB 提供的核心模板類
- 提供豐富的 CRUD 操作方法
- 支持復(fù)雜的查詢和聚合操作
- 需要手動編寫查詢邏輯
示例代碼:
查詢:
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)緯度附近的站點(diǎn) public List<StationLocation> nearbyStation(String latitude, String longitude) { //確定中心點(diǎn),根據(jù)經(jīng)緯度獲取站點(diǎn)信息 GeoJsonPoint point = new GeoJsonPoint(Double.parseDouble(longitude), Double.parseDouble(latitude)); //設(shè)置查詢半徑,查詢站點(diǎn)周邊50公里范圍的信息 Distance distance = new Distance(50, Metrics.KILOMETERS); //畫圓 確定查詢范圍 Circle circle = new Circle(point, distance); //查詢MongoDB數(shù)據(jù)庫中站點(diǎn)信息 Query query = new Query(Criteria.where("location").withinSphere(circle)); List<StationLocation> stations = mongoTemplate.find(query, StationLocation.class); }
4.2 MongoRepository
特點(diǎn):
- 基于 JPA 風(fēng)格的 Repository 接口
- 支持方法名自動生成查詢
- 提供基本的 CRUD 操作
- 可通過注解擴(kuò)展自定義查詢
- 適合簡單的 CRUD 操作
示例代碼:
創(chuàng)建Repository的接口
//StationLocation為要查詢的文檔對應(yīng)的實(shí)體類,String為實(shí)體類StationLocation主鍵的類型 public interface StationLocationRepository extends MongoRepository<StationLocation, String> { //方法要規(guī)范命名,mongodb才能按圖索驥找到對應(yīng)的數(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
特點(diǎn):
- 響應(yīng)式編程模型的 MongoTemplate
- 返回 Mono 或 Flux 類型
- 適合非阻塞、異步應(yīng)用
- 需要 Spring WebFlux 環(huán)境
示例代碼:
@Autowired private ReactiveMongoTemplate reactiveMongoTemplate; public Mono<User> findUserById(String id) { return reactiveMongoTemplate.findById(id, User.class); }
4.4 ReactiveMongoRepository
特點(diǎn):
- 響應(yīng)式版本的 MongoRepository
- 返回 Publisher 類型 (Mono/Flux)
- 支持響應(yīng)式流處理
- 適合全棧響應(yīng)式應(yīng)用
示例代碼:
// 創(chuàng)建ReactiveRepository public interface UserReactiveRepository extends ReactiveMongoRepository<User, String> { Flux<User> findByName(String name); } // 使用 @Autowired private UserReactiveRepository userReactiveRepository;
4.5 原生 MongoDB Java 驅(qū)動
特點(diǎn):
- 直接使用 MongoDB 官方 Java 驅(qū)動
- 不依賴 Spring Data 抽象層
- 最靈活但也最底層
- 需要手動處理更多細(xì)節(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ū)別對比
方式 | 編程模型 | 抽象級別 | 適用場景 | 學(xué)習(xí)曲線 |
---|---|---|---|---|
MongoTemplate | 命令式 | 中等 | 復(fù)雜查詢/操作 | 中等 |
MongoRepository | 命令式 | 高 | 簡單 CRUD | 低 |
ReactiveMongoTemplate | 響應(yīng)式 | 中等 | 響應(yīng)式復(fù)雜操作 | 較高 |
ReactiveMongoRepository | 響應(yīng)式 | 高 | 響應(yīng)式簡單 CRUD | 中等 |
原生驅(qū)動 | 命令式 | 低 | 需要直接控制 | 高 |
六、選擇建議
- 簡單 CRUD:優(yōu)先考慮 MongoRepository/ReactiveMongoRepository
- 復(fù)雜查詢/聚合:使用 MongoTemplate/ReactiveMongoTemplate
- 響應(yīng)式應(yīng)用:選擇 Reactive 版本
- 需要直接控制底層:使用原生驅(qū)動。
到此這篇關(guān)于Springboot+MongoDB簡單使用示例的文章就介紹到這了,更多相關(guān)Springboot MongoDB使用內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
解決java.lang.IllegalArgumentException: URI is
這篇文章主要介紹了解決java.lang.IllegalArgumentException: URI is not hierarchical報錯的問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2025-06-06使用Java的方式模擬Flutter的Widget實(shí)現(xiàn)多層括號嵌套
這篇文章主要介紹了使用Java的方式模擬Flutter的Widget的實(shí)現(xiàn)多層括號嵌套問題,本文給大家介紹的非常詳細(xì),具有一定的參考借鑒價值,需要的朋友可以參考下2019-07-07SpringBoot線程池ThreadPoolTaskExecutor異步處理百萬級數(shù)據(jù)
本文主要介紹了SpringBoot線程池ThreadPoolTaskExecutor異步處理百萬級數(shù)據(jù),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2024-03-03springboot+chatgpt+chatUI Pro開發(fā)智能聊天工具的實(shí)踐
本文主要介紹了springboot+chatgpt+chatUI Pro開發(fā)智能聊天工具的實(shí)踐,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-04-04Intellij IDEA 斷點(diǎn)不可用報錯 No executable 
這篇文章主要介紹了Intellij IDEA 斷點(diǎn)不可用報錯 No executable code found問題及解決方案,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-10-10Java關(guān)鍵字final的實(shí)現(xiàn)原理分析
這篇文章主要介紹了Java關(guān)鍵字final的實(shí)現(xiàn)原理分析,在JDK8之前,如果在匿名內(nèi)部類中需要訪問局部變量,那么這個局部變量一定是final修飾的,但final關(guān)鍵字可以省略,需要的朋友可以參考下2024-01-01詳解java創(chuàng)建一個女朋友類(對象啥的new一個就是)==建造者模式,一鍵重寫
這篇文章主要介紹了java建造者模式一鍵重寫,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-04-04