欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Springboot+MongoDB的五種操作方式

 更新時間:2025年07月28日 09:18:34   作者:moxiaoran5753  
本文主要介紹了Springboot+MongoDB的五種操作方式,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧

一、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)文章

最新評論