我正在尝试使用Spring Data MongoDB @LastModifiedDate
注释来引入审核。它适用于顶级文档,但我遇到了嵌入式对象的问题。
例如:
@Document(collection = "parent")
class ParentDocument {
@Id
String id;
@LastModifiedDate
DateTime updated;
List<ChildDocument> children;
}
@Document
class ChildDocument {
@Id
String id;
@LastModifiedDate
DateTime updated;
}
默认情况下,当我使用内部parentDocument
列表保存children
实例时,updated
值仅针对parentDocument
设置,但不会针对children
中的任何对象设置}列表。但在这种情况下,我也想审核它们。是否有可能以某种方式解决这个问题?
答案 0 :(得分:1)
我决定使用自定义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添加到应用程序上下文
<bean id="customAuditingEventListener" class="app.CustomAuditingEventListener"/>
答案 1 :(得分:0)
我不知道 DateTime
类型是什么,但是 LocalDateTime
下一个配置应该适用于 spring-boot-starter-data-mongodb-reactive
项目:
@Configuration
public class LastModifiedDateConfig implements ApplicationListener<BeforeConvertEvent<Object>> {
@Override
public void onApplicationEvent(BeforeConvertEvent<Object> event) {
Optional.ofNullable(event)
.map(MongoMappingEvent::getSource)
.filter(ParentDocument.class::isInstance)
.map(ParentDocument.class::cast)
.ifPresent(parentDocument -> parentDocument.updated = LocalDateTime.now());
Optional.ofNullable(event)
.map(MongoMappingEvent::getSource)
.filter(ChildDocument.class::isInstance)
.map(ChildDocument.class::cast)
.ifPresent(childDocument -> childDocument.updated = LocalDateTime.now());
}
}