Spring Boot 2.0.0响应式MongoDB无法向集合添加数据求助
MongoDB存储Person对象的实现梳理
看起来你已经搭好了基础的实体类和Repository,我来帮你梳理下这里的关键点,确保符合你期望的MongoDB存储格式:
核心需求回顾
- 存储
Person对象,每个实例关联一个notes集合 - 期望MongoDB中的最终存储结构:
{ "_id": ObjectId("..."), "name": "Bob", "notes": ["nice", "tall"] }
你的实体类实现
@Document @Builder(toBuilder = true) @AllArgsConstructor @NoArgsConstructor @Getter public class Person { @Id ObjectId id; private String name; @Singular private Set<String> notes; }
你的Repository定义
@Repository public interface PersonRepository extends ReactiveMongoRepository<Person, ObjectId> { // 这里应该是你未写完的Reactive MongoDB Repository接口 }
关键细节说明
关于
Set<String> notes与MongoDB数组的兼容性
MongoDB本身没有原生的Set类型,Spring Data MongoDB会自动把Java的Set序列化成MongoDB的数组类型,刚好匹配你期望的notes: ["nice", "tall"]格式,完全不用额外配置。@Singular注解的作用
这个注解配合@Builder使用,会帮你生成更友好的Builder方法:你可以用note("xxx")逐个添加笔记,而不是直接传入一个Set集合,比如:Person bob = Person.builder() .name("Bob") .note("nice") .note("tall") .build();这样构建对象时更灵活,最终生成的Set也会自动去重(符合Set的特性),序列化后依然是MongoDB数组。
Reactive Repository的使用
你继承的ReactiveMongoRepository是Spring Data MongoDB提供的响应式Repository接口,自带了基础的CRUD方法,比如save()、findById()等,直接用这些方法就能把Person对象保存到MongoDB中,完全满足你的存储需求。
内容的提问来源于stack exchange,提问作者billdoor
相关产品推荐
相关产品推荐

