java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > Springboot MongoDB使用

Springboot+MongoDB的五种操作方式

作者: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 #指定操作的数据库

三、创建mongodb文档对应的实体类

@Data
@Schema(description = "站点位置")
public class StationLocation
{

    @Schema(description = "id")
    @Id
    private 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

特点

示例代码:

查询:

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;

  // 调用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

特点

示例代码:

创建Repository的接口

//StationLocation为要查询的文档对应的实体类,String为实体类StationLocation主键的类型
public interface StationLocationRepository extends MongoRepository<StationLocation, String> {
    
	//方法要规范命名,mongodb才能按图索骥找到对应的数据
    StationLocation getByStationId(Long id);

}

调用上面定义的Repository新增插入数据:

 @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;
    }

修改数据

@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

特点

示例代码

@Autowired
private ReactiveMongoTemplate reactiveMongoTemplate;

public Mono<User> findUserById(String id) {
    return reactiveMongoTemplate.findById(id, User.class);
}

4.4 ReactiveMongoRepository

特点

示例代码

// 创建ReactiveRepository
public interface UserReactiveRepository extends ReactiveMongoRepository<User, String> {
    Flux<User> findByName(String name);
}

// 使用
@Autowired
private UserReactiveRepository userReactiveRepository;

4.5  原生 MongoDB Java 驱动

特点

示例代码

@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中等
原生驱动命令式需要直接控制

六、选择建议

到此这篇关于Springboot+MongoDB简单使用示例的文章就介绍到这了,更多相关Springboot MongoDB使用内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家! 

您可能感兴趣的文章:
阅读全文