springboot整合mongodb

本文介绍了Java Spring与MongoDB整合开发的步骤。包括添加依赖、在配置文件添加连接信息、创建实体类、编写Dao层,利用MongoRepository预定义方法及JPA命名规范定义查询方法,还提及调用自带方法和使用mongoTemplate进行条件查询。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.添加依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>

2.在application.properties中添加mongodb的连接信息

spring:
  data:
    mongodb:
      uri: mongodb://${objname.mongodb.user}:${objname.mongodb.password}@${objname.mongodb.host}:${objname.mongodb.port}/${objname.device.mongodb}

3.创建一个自定义表单的实体类

import lombok.Getter;
import lombok.Setter;
import lombok.experimental.Accessors;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.core.mapping.Field;

import java.util.Date;
import java.util.List;

@Getter
@Setter
@Accessors(chain = true)
//@Document注解表明这是一个文档类型。标注在实体类上,类似于hibernate的entity注解,表示由mongo来维护该表。
@Document("mongodb_database_name")
public class DeviceStatusHistory {
	//@CompoundIndex,复合索引,加复合索引后通过复合索引字段查询将大大提高速度。
	//@Id是主键,不可重复,自带索引,可以在定义的列名上标注,需要自己生成并维护不重复的约束。如果自己不设置@Id主键,mongo会自动生成一个唯一主键,并且插入时效率远高于自己设置主键。
    @Id
    private String id;

	//@Transient,被该注解标注的,将不会被录入到数据库中。只作为普通的javaBean属性。
	@Transient
	private String name;

    @Field("device_id")
    private String deviceId;
}

4.编写Dao层

定义一个接口,继承MongoRepository,MongoRepository中已经预定义了一些增删查的方法,根据JPA的命名规范可以定义一些查询方法,不需要具体实现,底层会帮你实现。

import com.countrygarden.bdr.ioraip.device.history.orm.model.DeviceStatusHistory;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;

@Repository("DeviceStatusHistoryRepository")
public interface DeviceStatusHistoryRepository extends MongoRepository<DeviceStatusHistory, String> {

}

5.调用自带的方法

@Service
public class SomeService {

    @Autowired
    private DeviceStatusHistoryRepository historyRepository;

    public void insertDataTester(DeviceStatusHistory history) {
        DeviceStatusHistory save = historyRepository.save(history);
    }

    public void findAllTester() {
        List<DeviceStatusHistory> all = historyRepository.findAll();
    }
}

6.使用mongoTemplate优雅地条件查询需要字段

数据格式

{
    "_id" : "1",
    "userId" : "2",
    "bookId" : "1",
    "historyList" : [ 
        {
            "_id" : "1",
            "hh" : "1"
        }, 
        {
            "_id" : "2",
            "hh" : "2"
        }, 
        {
            "_id" : "3",
            "hh" : "2"
        }
    ],
    "_class" : "com.domain.UseHistory"
}

@Service
public class MongodbStatusStorageServiceImpl{
	
	// 只需要注入就能用
    @Autowired
    private MongoTemplate mongoTemplate;

    public void find() {
        History history = null;
        //封装对象列表查询条件
        List<AggregationOperation> commonOperations = new ArrayList<>();
        //1. 指定查询主文档
        MatchOperation match = Aggregation.match(Criteria.where("userId").is("2"));
        commonOperations.add(match);
        //2. 指定投影,返回哪些字段
        ProjectionOperation project = Aggregation.project("historyList");
        commonOperations.add(project);
        //3. 拆分内嵌文档
        UnwindOperation unwind = Aggregation.unwind("historyList");
        commonOperations.add(unwind);
        //4. 指定查询子文档
        MatchOperation match2 = Aggregation.match(
                Criteria.where("historyList.hh").is("2"));
        commonOperations.add(match2);

        //创建管道查询对象
        Aggregation aggregation = Aggregation.newAggregation(commonOperations);
        AggregationResults<JSONObject> reminds = mongoTemplate.aggregate(aggregation, "history", JSONObject.class);
        List<JSONObject> mappedResults = reminds.getMappedResults();
        if (mappedResults != null && mappedResults.size() > 0) {
            history = JSONObject.parseObject(mappedResults.get(0).getJSONObject("historyList").toJSONString(), History.class);
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值