Spring Reactive MongoDB中@DocumentReference关联字段空指针问题求助
Spring Reactive MongoDB 一对多关联空指针问题解决
问题原因
- 使用
@DocumentReference(lazy = true)时,若用户无关联Post数据,Spring Data MongoDB不会自动将posts初始化为空列表,而是保留为null - 业务代码中直接调用
existingUser.getPosts().isEmpty(),未做null校验,触发空指针异常
解决方案
1. 实体类初始化空列表(推荐)
在User实体中直接给posts字段初始化空列表,从根源避免null:
@Document(collection = "user") public class User { @Id private String id; private String name; private String email; @DocumentReference(lazy = true) private List<Post> posts = new ArrayList<>(); // 初始化空列表 }
2. 业务方法增加null安全判断
若不想修改实体类,在处理前先判断posts是否为null:
public Flux<PostDTO> findPosts(String id) { return repository.findById(id) .flatMapMany(existingUser -> { List<Post> posts = existingUser.getPosts(); // 先判断null,再处理空列表场景 if (posts == null || posts.isEmpty()) { return Flux.empty(); } List<PostDTO> list = posts.stream().map(PostDTO::new).toList(); return Flux.fromIterable(list); }) .switchIfEmpty(Mono.error(new ResourceNotFoundException("Recurso não encontrado"))); }
补充说明
@DocumentReference(lazy = true)是延迟加载,仅当实际访问posts属性时才会查询关联数据;但如果用户本身无关联Post记录,MongoDB不会返回数据,此时posts会保持null(除非提前初始化)- 原代码中
if (existingUser.getPosts().isEmpty())后未加大括号,Flux.empty();属于无效代码,修正后需通过return返回空流
内容的提问来源于stack exchange,提问作者Alexandre
相关产品推荐
相关产品推荐

