问题描述
我正在尝试使用 Spring Data MongoDB @LastModifiedDate
注释来引入审计.它适用于顶级文档,但我遇到了嵌入对象的问题.
I'm trying to introduce auditing by using Spring Data MongoDB @LastModifiedDate
annotation. It works fine for top-level documents but I've faced with the problem for embedded objects.
例如:
@Document(collection = "parent")
class ParentDocument {
@Id
String id;
@LastModifiedDate
DateTime updated;
List<ChildDocument> children;
}
@Document
class ChildDocument {
@Id
String id;
@LastModifiedDate
DateTime updated;
}
默认情况下,当我使用内部 children
列表保存 parentDocument
实例时,仅为 parentDocument
设置 updated
值> 但不适用于 children
列表中的任何对象.但在这种情况下,我也想审计它们.有没有可能以某种方式解决这个问题?
By default, when I save parentDocument
instance with inner children
list, updated
value is set only for parentDocument
but not for any object from the children
list. But in this case I want to audit them too. Is it possible to solve this problem somehow?
推荐答案
我决定使用自定义 ApplicationListener
public class CustomAuditingEventListener implements
ApplicationListener<BeforeConvertEvent<Object>> {
@Override
public void onApplicationEvent(BeforeConvertEvent<Object> event) {
Object source = event.getSource();
if (source instanceof ParentDocument) {
DateTime currentTime = DateTime.now();
ParentDocument parent = (ParentDocument) source;
parent.getChildren().forEach(item -> item.setUpdated(currentTime));
}
}
}
然后在应用上下文中添加相应的bean
And then add corresponding bean to the application context
<bean id="customAuditingEventListener" class="app.CustomAuditingEventListener"/>
这篇关于Spring Data MongoDB 审计不适用于嵌入式文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!