最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Springboot+MongoDB的五種操作方式

 更新時間:2025年07月28日 09:18:34   作者:moxiaoran5753  
本文主要介紹了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 驅動

特點

  • 直接使用 MongoDB 官方 Java 驅動
  • 不依賴 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中等
原生驅動命令式需要直接控制

六、選擇建議

  • 簡單 CRUD:優(yōu)先考慮 MongoRepository/ReactiveMongoRepository
  • 復雜查詢/聚合:使用 MongoTemplate/ReactiveMongoTemplate
  • 響應式應用:選擇 Reactive 版本
  • 需要直接控制底層:使用原生驅動。

到此這篇關于Springboot+MongoDB簡單使用示例的文章就介紹到這了,更多相關Springboot MongoDB使用內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家! 

相關文章

  • 教你Java中的Lock鎖底層AQS到底是如何實現(xià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獲取Bean的九種方法詳解

    淺析Spring獲取Bean的九種方法詳解

    隨著SpringBoot的普及,Spring的使用也越來越廣,在某些場景下,我們無法通過注解或配置的形式直接獲取到某個Bean。比如,在某一些工具類、設計模式實現(xiàn)中需要使用到Spring容器管理的Bean,此時就需要直接獲取到對應的Bean,這篇文章主要介紹了Spring獲取Bean的九種方法
    2023-01-01
  • Spring SpringMVC在啟動完成后執(zhí)行方法源碼解析

    Spring SpringMVC在啟動完成后執(zhí)行方法源碼解析

    這篇文章主要介紹了SpringMVC在啟動完成后執(zhí)行方法源碼解析,還是非常不錯的,在這里分享給大家,需要的朋友可以參考下。
    2017-09-09
  • springmvc fastjson 反序列化時間格式化方法(推薦)

    springmvc fastjson 反序列化時間格式化方法(推薦)

    下面小編就為大家?guī)硪黄猻pringmvc fastjson 反序列化時間格式化方法(推薦)。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2017-04-04
  • 使用HandlerMethodArgumentResolver用于統(tǒng)一獲取當前登錄用戶

    使用HandlerMethodArgumentResolver用于統(tǒng)一獲取當前登錄用戶

    這篇文章主要介紹了使用HandlerMethodArgumentResolver用于統(tǒng)一獲取當前登錄用戶實例,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-12-12
  • 多jdk環(huán)境下指定springboot外部配置文件詳解

    多jdk環(huán)境下指定springboot外部配置文件詳解

    這篇文章主要為大家介紹了多jdk環(huán)境下指定springboot外部配置文件詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2023-03-03
  • 基于SpringBoot框架管理Excel和PDF文件類型

    基于SpringBoot框架管理Excel和PDF文件類型

    這篇文章主要介紹了基于SpringBoot框架,管理Excel和PDF文件類型,本文給大家介紹的非常詳細,具有一定的參考借鑒價值,需要的朋友可以參考下
    2020-02-02
  • 淺談@RequestMapping注解的注意點

    淺談@RequestMapping注解的注意點

    這篇文章主要介紹了淺談@RequestMapping注解的注意點,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-02-02
  • jedis操作redis的幾種常見方式總結

    jedis操作redis的幾種常見方式總結

    Redis是一個著名的key-value存儲系統(tǒng),也是nosql中的最常見的一種,這篇文章主要給大家總結了關于在java中jedis操作redis的幾種常見方式,文中給出了詳細的示例代碼供大家參考學習,需要的朋友們下面來一起看看吧。
    2017-05-05
  • 利用Java實現(xiàn)圖片馬賽克效果

    利用Java實現(xiàn)圖片馬賽克效果

    馬賽克效果是一種常見的圖像處理技術,通過將圖像劃分為多個小塊并對每個小塊進行平均色處理,模擬馬賽克的效果,在本項目中,我們將使用Java的Swing庫和圖像處理技術來實現(xiàn)圖片的馬賽克特效,需要的朋友可以參考下
    2025-02-02

最新評論

固安县| 长葛市| 田东县| 崇礼县| 玉屏| 穆棱市| 扎兰屯市| 高平市| 汝州市| 吴堡县| 婺源县| 繁峙县| 海伦市| 壤塘县| 黄大仙区| 望江县| 晋宁县| 宜君县| 绥芬河市| 马尔康县| 富民县| 宝兴县| 琼中| 海伦市| 屯留县| 连南| 五寨县| 拜城县| 隆林| 东方市| 共和县| 宕昌县| 旬邑县| 孙吴县| 马龙县| 阳东县| 电白县| 宜阳县| 民丰县| 四子王旗| 黔江区|