我对MongoDB中的级联有疑问; 所以。我的项目基于Java 10和Spring Boot 2.0.5和Lombok。 我已经创建了CascadeSave事件侦听器,就是这样
public class CascadeSaveMongoEventListener extends AbstractMongoEventListener {
@Autowired
private MongoOperations mongoOperations;
@Override
public void onBeforeConvert(BeforeConvertEvent event) {
Object source = event.getSource();
ReflectionUtils.doWithFields(source.getClass(), field -> {
ReflectionUtils.makeAccessible(field);
if (field.isAnnotationPresent(DBRef.class) && field.isAnnotationPresent(CascadeSave.class)) {
Object fieldValue = field.get(source);
if (fieldValue instanceof Collection<?>) {
Collection collection = (Collection<?>) fieldValue;
for (Object o : collection) {
mongoOperations.save(o);
}
} else {
mongoOperations.save(fieldValue);
}
}
});
}
}
事件监听器也包含在mongo配置中,如下所示:
@Bean
public CascadeSaveMongoEventListener cascadingMongoEventListener() {
return new CascadeSaveMongoEventListener();
}
域类的外观如下:
@Data
@AllArgsConstructor
@NoArgsConstructor
@Document
public class Article {
@Id
private String id;
@DBRef(lazy = true)
@CascadeSave
private List<Comment> comments;
}
@Data
@AllArgsConstructor
@NoArgsConstructor
@Document
public class Comment {
@Id
private String id;
private String text;
}
问题是保存后,我通过Mongo Compass看了一下数据库,Article.comments是null的集合,但是注释正确地保存在单独的集合中。问题是什么?谢谢!